PostSharp6.5//Logging/Configuring Specific Logging Frameworks/Logging with ASP.​NET Core

Logging with ASP.NET Core

This article shows how to use PostSharp Logging and ASP.NET Core logging together.

To use PostSharp Logging with the logging system of ASP.NET Core:

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

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

  3. Set up ASP.NET Core logging in your CreateHostBuilder like this:

    C#
    public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
        .ConfigureLogging(loggingBuilder =>
        {
          loggingBuilder.ClearProviders();
          loggingBuilder.AddConsole();
        })
        .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
  4. In appsettings.json and appsettings.Development.json, reduce the minimum logged LogLevel to Debug. PostSharp outputs most traces at the Debug level:

    json
    {
      "Logging": {
        "LogLevel": {
          "Default": "Debug",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      }
    }
  5. Set MicrosoftLoggingBackend as the default backend in your Main method:

    C#
    IHost host = CreateHostBuilder(args).Build();
    var loggerFactory = (ILoggerFactory) host.Services.GetService(typeof(ILoggerFactory));
    LoggingServices.DefaultBackend = new MicrosoftLoggingBackend(loggerFactory);
    host.Run();

Any methods annotated with LogAttribute will now emit log messages into ASP.NET Core logging, as in this example:

dbug: WebSite1.Pages.RazorPage1[2]
      RazorPage1.HelloWorld() | Starting.
dbug: WebSite1.Pages.RazorPage1[4]
      RazorPage1.HelloWorld() | Succeeded.
See Also