log4netlog4net-configuration

How do I use a date pattern in a header/footer?


Here's my appender configuration from my app.config. This just prints out the literal string instead of translating it to the date (i.e., it literally prints "[START: %date{MM/dd/yy HH:mm} ]").

<appender name="RollingLogFileAppender"
          type="log4net.Appender.RollingFileAppender">
  <file value="C:\somelog" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <datePattern value="-yyyy-MM-dd'.txt'" />
  <layout type="log4net.Layout.PatternLayout">
    <header value="[START:  %date{MM/dd/yy HH:mm} ]&#13;&#10;" />
    <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} - %message" />
    <footer value="[END]&#13;&#10;&#13;&#10;" />
  </layout>
</appender>

How can I get this to print the date/time in the header?


Solution

  • An easy way to do this is to subclass log4net.Layout.PatternLayout and override Header and Footer. Then you can add whatever you want to your Header: date stamp, machine name, user name, assembly version, or whatever your heart desires:

    using System;
    using log4net.Layout;
    
    namespace MyAssembly
    {
        class MyPatternLayout : PatternLayout
        {
            public override string Header
            {
                get
                {
                    var dateString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    return string.Format("[START:  {0} ]\r\n", dateString);
                }
            }
        }
    }
    

    Include this new class in your assembly, and use the new type in your file, like this:

    <layout type="MyAssembly.MyPatternLayout">
        <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss} - %message" />
    </layout>
    

    Since you overrode Header and Footer, you don't even need to add it here. The Header will be added every time your application starts, and every time the file rolls over.