Thursday, December 11, 2008

Log4Net ConversionPattern Strings

Several months ago we began to transition from an in-house logging framework to Log4Net in our primary web applications. For the last couple of days I have been trying to troubleshoot some production problems in the two of these applications and I noticed that my Log4Net logs were using a 12hr clock for the timestamp, and didn't include an AM/PM indicator. It also used old style parameter names rather than the newer verbose parameters.

Seeing as how I tend to cut and paste code for things like that, and I know other programmers do as well, I figured I would blog about what I am switching to, as well as a couple of other options. In case you are not really familiar with log4net, this setting is changed by editing the value string for the ConversionPattern param in the - log4net --appender - section of the web or app config file:

<param name="ConversionPattern" value="your string here"/>


The old:
value="%-5p %d{yyyy-MM-dd hh:mm:ss} - %m%n"
Results in:
ERROR 2008-12-03 01:28:38 - login.aspx submitted for 7234

Besides the timestamp problem, the format string is difficult to understand. It is not at all obvious what 'p', 'd', 'm' and 'n' stand for. Well, maybe the fact that 'd' is followed by a date format string you could guess that it stood for Date.

The following link lists both the shortcut and the verbose fomat values from the Apache log4net documentation.

The one I am switching to:
value="%-5level %date{yyyy-MM-dd HH:mm:ss} - %message%newline">

Note the more obvious setting names. This value string results in:
INFO 2008-12-11 14:06:59 - login.aspx submitted for 7234


Other choices:
value="%-5level %date{G} - %message%newline">
Results in
INFO 12/11/2008 2:15:07 PM - login.aspx submitted for 7234

value="%-5level %date{yyyy-MM-dd hh:mm:ss t} - %message%newline">
Results in
INFO 2008-12-11 02:06:59 P - login.aspx submitted for 7234

value="%-5level %date{G} - %message%newline">
Results in
INFO 12/11/2008 2:15:07 PM - login.aspx submitted for 7234

value="%-5level %date{u} - %message%newline"
Results in (not this is UTC time)
INFO 2008-12-11 14:06:59Z - login.aspx submitted for 7234

Those of you familiar with date string formats in the .Net framework will recognize some of these strings. The Log4Net framework allows you to use any date format that is valid in a ToString() call in the .Net framework. For additional format strings see the MSDN Format String Documentation.

2 comments:

Mike Knowles said...

Just what I needed, thanks.

Anonymous said...

In most applications it's wise to include [%thread] in the pattern.
Example: %date [%thread] %-6level %logger - %message %exception%newline