Post­Sharp Documentation / Logging / Configuring specific logging frameworks / Logging to log4net

Logging to log4net

This article shows how to use PostSharp Logging and log4net together.

To use PostSharp Logging with log4net:

  1. Add PostSharp logging to your codebase as described in Adding Detailed Logging to your Solution.

  2. Add the PostSharp.Patterns.Diagnostics.Log4Net package to your startup project.

  3. Create an XML file named log4net.config. In the file properties, set the Copy to Output Directory property to Copy always.

    Add the following content to this file:

    <log4net>
      <appender name="file" type="log4net.Appender.FileAppender">
    
        <file value="log4net.log" />
    
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger %ndc - %message%newline" />
        </layout>
      </appender>
    
      <appender name="console" type="log4net.Appender.ColoredConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
        </layout>
      </appender>
    
      <root>
        <level value="DEBUG" />
        <appender-ref ref="file" />
        <appender-ref ref="console" />
      </root>
    
    </log4net>

    This example configuration file instructs log4net to write all log records to a file named log4net.log and to the console.

    See the log4net documentation for details about this configuration file.

  4. In the application startup file, include the following namespace imports:

    C#
    using log4net.Config;
    using PostSharp.Patterns.Diagnostics;
    using PostSharp.Patterns.Diagnostics.Backends.Log4Net;

    In the application startup method, include the following code:

    C#
    // Configure Log4Net
    XmlConfigurator.Configure(new FileInfo("log4net.config"));
    
    // Configure PostSharp Logging to use Log4Net
    LoggingServices.DefaultBackend = new Log4NetLoggingBackend();

If you run your application, you should now see a detailed log in a file named log4net.log. If your application is a console application, you should also see the log in the console.

See Also