PostSharp 5.0 / / Post­Sharp Documentation / Logging / Configuring specific logging frameworks / Logging to NLog

Logging to NLog

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

To use PostSharp Logging with NLog:

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

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

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

    using NLog;
    using NLog.Config;
    using NLog.Targets;
    using PostSharp.Patterns.Diagnostics;
    using PostSharp.Patterns.Diagnostics.Backends.NLog;

    In the application startup method, include the following code:

    // Configure NLog.
    var nlogConfig = new LoggingConfiguration();
    var fileTarget = new FileTarget("file")
        FileName = "nlog.log",
        KeepFileOpen = true,
        ConcurrentWrites = false,
    nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget));
    var consoleTarget = new ConsoleTarget("console");
    nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget));
    // Configure PostSharp Logging to use NLog.
    LoggingServices.DefaultBackend = new NLogLoggingBackend(new LogFactory(nlogConfig));

    This example code instructs NLog to write all log records to a file named nlog.log and to the console. If you prefer, you can configure NLog with a configuration file. See the NLog documentation for details.

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

See Also