views:

694

answers:

2

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?

A: 

If you haven't found a solution, you would need to download the source code and digg a little deeper than I did. I couldn't see where at any point any pattern matching and formatting was done against the header/footers so they just might be literal values. Even CR LF Needs to be written in it's XML numeric character reference.

If you did find a solution, please post it. You just might have to change the source to perform pattern matching on the headers and footers.

NTulip
+3  A: 

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.

pduncan
Do you have any links to examples of subclassing the PatternLayout class?
User
I've added an example to the answer for you.
pduncan
Is there a way to override the Header such that it uses the value attribute of the header element in you xml configuration like the PatternLayout class does?
User
I'm not sure without downloading the source code. But even if you could do this, wouldn't this just put you back to your original problem?
pduncan