Thursday, August 30, 2012

Logging made simple


This may be old news for most, but for those of you who have not used log4net, this could be quite beneficial…

Log4net is a complete logging solution to keep a detailed audit log of your application as necessary with a variety of different output sources, namely:
  • AdoNetAppender
  • MS SQL Server
  • MS Access
  • Oracle9i
  • Oracle8i
  • IBM DB2
  • SQLite
  • AspNetTraceAppender
  • BufferingForwardingAppender
  • ColoredConsoleAppender
  • ConsoleAppender
  • EventLogAppender
  • FileAppender
  • ForwardingAppender
  • ManagedColoredConsoleAppender
  • MemoryAppender
  • NetSendAppender
  • OutputDebugStringAppender
  • RemotingAppender
  • RollingFileAppender
  • SmtpAppender
  • SmtpPickupDirAppender
  • TraceAppender
  • UdpAppender
The following levels can also be specified in the configuration file as filters to be logged as necessary:
  • Trace
  • Debug
  • Error 
  • Fatal
  • Info
  • Warn
Log4Net allows you to log your application status with a single line of code and the rest is all specified in the configuration file for flexibility and ease.

So effectively you could delegate for example, all of your error level messages to a database output source and the debug level messages to file or whichever you choose… There are also conversion patterns for you to specify in the configuration file to format how and what data will be written to a file output for example…

PM> Install-Package log4net

Usage:
ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Log.Error("My error message", exception);
Log.Debug("My debug message");

log4net.config:

<?xml version="1.0"?>
<log4net debug="false">
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger %ndc - %message%newline" />
    </layout>
  </appender>

  <appender name="FileAppender" type="log4net.Appender.RollingFileAppender, log4net" >
    <param name="File" value="MyLog.log" />
    <param name="AppendToFile" value="true" />
    <param name="RollingStyle" value="Date" />
    <param name="DatePattern" value="yyyy.MM.dd" />
    <param name="StaticLogFileName" value="true" />
    <layout type="log4net.Layout.PatternLayout, log4net">
      <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
      <levelMin value="INFO" />
    </filter>
  </appender>
  <root>
    <level value="WARN" />
    <appender-ref ref="ConsoleAppender" />
  </root>

  <logger name="MyLogger">
    <level value="INFO" />
  </logger>
</log4net>

Till next time, happy logging...

1 comment:

  1. Nice post. I've found this to be a very simple but powerful logging library.

    ReplyDelete