PostSharpLoggingConnecting to Source and Target Logging FrameworksLogging with Serilog
Open sandboxFocusImprove this doc

Logging with Serilog

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

Writing PostSharp Logging events to Serilog

To send PostSharp Logging events to Serilog sinks:

  1. Add PostSharp logging to your codebase as described in Getting Started with PostSharp Logging.

  2. Add the PostSharp.Patterns.Diagnostics.Serilog package to your startup project, as well as the packages for all Serilog sinks you will need. For the next code examples, install the packages Serilog.Sinks.ColoredConsole and Serilog.Sinks.File.

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

    using PostSharp.Patterns.Diagnostics;
    using PostSharp.Patterns.Diagnostics.Backends.Serilog;
    using Serilog;
    

    In the application startup method, include the following code:

    // The output template must include {Indent} for nice output.
    const string template = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Indent:l}{Message}{NewLine}{Exception}";
    
    // Configure a Serilog logger.
    var logger = new LoggerConfiguration()
      .MinimumLevel.Debug()
      .WriteTo.File("serilog.log", outputTemplate: template)
      .WriteTo.ColoredConsole(outputTemplate: template)
      .CreateLogger();
    
    // Configure PostSharp Logging to use Serilog
    LoggingServices.DefaultBackend = new SerilogLoggingBackend(logger);
    

    This example code instructs Serilog to write all log records to a file named serilog.log and to the console.

    Note that this code snippet supplies a custom output template. By default, Serilog does not indent the logs generated by PostSharp. PostSharp passes the indentation string to Serilog as a parameter named Indent. In order to produce indented logs, you need to include the {Indent:l} parameter into your output template.

    See the Serilog documentation for more details.

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

Using Serilog formatters instead of PostSharp ones

By default, PostSharp Logging will use its own formatters to format parameter values into a string and will pass the already-formatted string to Serilog.

If you want the unformatted parameter value to be passed to Serilog instead of the string, set the UseSerilogFormatters property to true.

Including more semantic parameters

By default, PostSharp Logging passes the following pieces of information to Serilog as semantic parameters: parameter values, return values, this value, and execution time. Other pieces of information such as for instance the type and method name are included in the message template.

If you want pass more pieces of information as semantic parameters, set the SemanticParametersTreatedSemantically and IncludedSpecialProperties properties.

Note

Semantic parameters have a relatively high performance cost in Serilog. We suggest you do not use more semantic parameters than necessary.

Collecting Serilog events into PostSharp Logging

If your source code already emits log events using Serilog, you can configure PostSharp Logging to collect log events directly emitted by the Serilog API, so that they are all processed by the same PostSharp backend and Serilog logger. One of the benefits is that indentation of manual logging and automatic logging will be synchronized. See Collecting Logs from Other Frameworks for more information.

Suppose that you have already configured Serilog and PostSharp like this:

// Configure Serilog
ILogger logger = new LoggerConfiguration()
   .MinimumLevel.Debug()
   .WriteTo.ColoredConsole()
   .CreateLogger();

// Configure PostSharp Logging to use Serilog
LoggingServices.DefaultBackend = new SerilogLoggingBackend(logger); 

// Emit manual log records. Note that this logger will skip PostSharp Logging, so indentation
// will not be respected.
logger.Information("Hello, world.");

To collect Serilog manual logging events into PostSharp, replace that startup code with the following:

// Create a Serilog logger that writes to the final output (e.g. ColoredConsole).
// You would typically copy the configuration code of your original logger, but you would give it a different name.
ILogger outputLogger = new LoggerConfiguration()
   .MinimumLevel.Debug()
   .WriteTo.ColoredConsole()
   .CreateLogger();

// Use this output logger to create a PostSharp backend and set it as the default backend:
LoggingServices.DefaultBackend = new SerilogLoggingBackend(outputLogger); 

// Create a second Serilog logger that sends all logging events to the PostSharp collector.
// This becomes your new front-end logger, the one you will actually use to emit log records.
var logger = new LoggerConfiguration()
   .MinimumLevel.Verbose()  // The verbosity here must be higher or equal to the one of 'outputLogger'.
   .WriteTo.PostSharp()
   .CreateLogger();

You can now do standard Serilog logging and the logging output will be collected and sent to PostSharp Logging. Use logger:

logger.Information("Hello, world.");

See Also

Reference

SerilogLoggingBackend
Other Resources

Collecting Logs from Other Frameworks