This article shows how to use PostSharp Logging and ASP.NET Core logging together.
Writing PostSharp Logging events to ASP.NET Core
To send PostSharp Logging events to the logging system of ASP.NET Core:
Add PostSharp Logging to your codebase as described in Getting Started with PostSharp Logging.
Add the
PostSharp.Patterns.Diagnostics.Microsoftpackage to your startup project.In Program.cs, set up ASP.NET Core logging like this:
var builder = WebApplication.CreateBuilder( args ); builder.Logging.ClearProviders(); builder.Logging.AddConsole();In appsettings.json and appsettings.Development.json, reduce the minimum logged
LogLeveltoDebug. PostSharp outputs most traces at theDebuglevel:{ "Logging": { "LogLevel": { "Default": "Debug", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } } }After you build the application, and before you run it, set MicrosoftLoggingBackend as the default backend:
var app = builder.Build(); var loggerFactory = app.Services.GetRequiredService<ILoggerFactory>(); LoggingServices.DefaultBackend = new MicrosoftLoggingBackend( loggerFactory );
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.
Collecting ASP.NET Core logging events into PostSharp Logging
If your source code already emits log events using the ILogger interface of .NET Core, you can configure PostSharp Logging to collect log events directly emitted by ILogger, so that they are all processed by the same PostSharp backend and 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.
To collect .NET Core manual logging events into PostSharp:
Add the
PostSharp.Patterns.Diagnostics.Microsoftpackage to your startup project.In Program.cs, after you create the
WebApplicationBuilder, add the following code:// First, create a logger factory with your final logging providers. These are the providers, // such as console or a log file, where you want the final output of logging to go: var outputLoggerFactory = LoggerFactory.Create( logging => logging .AddConfiguration( builder.Configuration.GetSection( "Logging" ) ) .AddConsole() ); // Next, use this logger factory to create a PostSharp backend and set it as the default backend: LoggingServices.DefaultBackend = new MicrosoftLoggingBackend( outputLoggerFactory ); // Finally, replace the logging providers of the application with the PostSharp logging provider, // which sends all events to PostSharp: builder.Logging.ClearProviders(); builder.Logging.AddPostSharp();
Now, you can use LogAttribute to add automatic logging and ILogger loggers to add manual log messages.
See Also
Reference
MicrosoftLoggingBackend
MicrosoftLoggingCollectingLoggerProvider
Other Resources