Friday, June 15, 2012

Setting up Log4Net

A task that needs to be done for almost every new project is the setting up of Log4Net. So here I am documenting the steps needed, for future reference.


  1. Download the Log4Net dll from the correct website. This can be found here:  http://logging.apache.org/log4net/index.html
  2. Make sure you downloaded the correct version (Mono /.Net / etc)
  3. Also, make sure the DLL you downloaded is authentic. Checks its MD5 or PGP.
  4. Move the DLL to a folder within your project.
  5. Add a reference to this DLL.
  6. Add the line: log4net.Config.XmlConfigurator.Configure(); to your project.  If your project is ASP.NET, this should go within Application_Start() under Global.asax.cs
  7. Ideally in this location you also call the logger itself, by logging something. This avoids a weird bug which stops logging in release mode.
  8. If your configuration file for log4net is a separate file (which is recommended) add this line [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]  to AssemblyInfo.cs.  
  9. This guarantees that log4net keeps a lookout for changes to this file.
  10. Add two using statements to your class where you want to call the logger: 
    • using log4net; 
    • using System.Reflection;
  11. Create an instance for the logger: private ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  12. Call the logger, as shown:  logger.Info("Hello World!");
  13. Add Apache license to your source code:
Copyright (c) [yyyy] [company]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

  • The config itself should be similar to what is seen below:



<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    </configSections>
    <log4net>
        <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="..\Logs\MyLogger.log" />
            <appendToFile value="true" />
            <maximumFileSize value="100MB" />
            <maxSizeRollBackups value="20" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%d [%t] %-2p %c [%x] - %m%n"/>
            </layout>
        </appender>
        <root>
            <level value="ALL"/>
            <appender-ref ref="RollingFileAppender"/>
        </root>
    </log4net>
</configuration>

No comments: