Monday, March 24, 2008

Simple Logging in Your .NET Application

Logging can be a very useful tool when developing any application. Furthermore, logging is a must when deploying applications to a production environment. Keeping track of errors and informational messages can help you greatly reduce the time it takes to debug and fix a problem. As in any language, there is more than one way to enable logging in .NET. This article will cover getting started with logging using the free log4net framework.

To Get Started

  1. Get log4net from
  2. Create a sample .NET application that and call it "sampleLoggingApp"
  3. Create a place to store the log4net DLL, I usually create a "dependencies" directory
  4. Copy the extracted log4net DLL from "bin\net\2.0\release\log4net.dll" to your "dependencies" directory
  5. Set your Visual Studio to show all files, include the log4net DLL in your project and add a reference to it in your project

The Fun Stuff


  1. Create your log4net configuration file, we will call it log4net.config to keep appending to the same file:

      <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="sampleLog.log" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
        <level value="DEBUG" />
        <appender-ref ref="RollingLogFileAppender" />

  2. Set the path to the log4net.config file:

    private static String m_log4netConfigFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "log4net.config");

    This sets the path of the log4net.config file to be in the same directory are your executable.

  3. Create a static log instance:
    private static readonly ILog m_log = LogManager.GetLogger(typeof(Form1));

    Where "Form1" is the name of your application instance.
  4. Set a build event in Visual Studio that will copy the log4net configuration file in the output directory on every build:

    xcopy /y "$(ProjectDir)log4net.config" "$(TargetDir)"

  5. Write some information to the log:

    m_log.Debug("Inside Form1_Load");

More Information

I have covered the basics of getting started. However, log4net has quite a few more possible configurations such as

  • Log to a database table
  • Log to the console
  • Log to the event log
  • Log to an email address

More information for each configuration can be found at



  1. Optionally there are a few xsd files available online, one I created. I suggets binding one to the log4net element as they can guide you through the configuration options. To use the xsd located at:

    Simply modify your log4net element as follows:

    <log4net xsi:noNamespaceSchemaLocation="" xmlns:xsi="">


// //]]>