Setup Log4Net for a project in less than 2 minutes

Sometimes documentation is plain anoying. I've been using log4j since ... I don't know, maybe 5-6 years? The setup was as simple as dropping a log4j.xml into the class path and using the logger right away.

Log4Net ist not really much more complicated, but it requires a little bit more attention. Here is what you need to start logging via log4net in less than 2 minutes:

  • Grab the log4net zip over at: http://logging.apache.org/log4net/download.html
  • Copy the log4net.dll (for instance bin\net\2.0\release in the zip archive) into your project. Ignore the other zip content if you don't care.
  • Add the library reference
  • Create an App.Config file using the big xml chunk provided below
  • Call log4net.Config.XmlConfigurator.Configure(); once to initialize the log4net stack
  • Done
  1. <?xml version="1.0" encoding="utf-8" ?>
  2.  
  3. <configuration>
  4.  
  5. <configSections>
  6. <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  7. </configSections>
  8.  
  9. <log4net debug="true">
  10. <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender,log4net" >
  11. <param name="File" value="Debug.log" />
  12. <param name="AppendToFile" value="true" />
  13. <maximumFileSize value="10MB" />
  14. <maxSizeRollBackups value="2" />
  15. <layout type="log4net.Layout.PatternLayout,log4net">
  16. <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n" />
  17. </layout>
  18. </appender>
  19. <root>
  20. <priority value="ALL" />
  21. <appender-ref ref="LogFileAppender" />
  22. </root>
  23. </log4net>
  24.  
  25. </configuration>
some hints and tips to make your life easier:

Here is a pretty elegant way to obtain a logger with the category automatically set to the current class - (there is no equivalent to this in Java by the way - at least not for static fields)

  1. private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

The Logfile will be created next to the executable. Oh, and just in the case you did not know, you can use system envoronment variables in the App.config. For instance you could be foolish (or lazy if you prefer) and log directly onto the Windows system drive:

  1. <param name="File" value="${SystemDrive}\Debug.log" />