This article shows how to use PostSharp Logging and Common.Logging together.
To use PostSharp Logging with Common.Logging:
Add PostSharp Logging to your codebase as described in Getting Started with PostSharp Logging.
Add the
PostSharp.Patterns.Diagnostics.CommonLoggingpackage to your startup project.In the application startup file, include the following namespace imports:
using Common.Logging; using Common.Logging.Simple; using PostSharp.Patterns.Diagnostics; using PostSharp.Patterns.Diagnostics.Backends.CommonLogging;In the application startup method, include the following code:
// Configure Common.Logging to direct outputs to the system console. LogManager.Adapter = new ConsoleLoggerFactoryAdapter(); // Configure PostSharp Logging to direct outputs to Common.Logging. LoggingServices.DefaultBackend = new CommonLoggingLoggingBackend();This example code instructs Common.Logging to write all log records to the system console. See the Common.Logging documentation for details. Common.Logging for .NET Standard does not include a console adapter.
ConsoleLoggerFactoryAdapteris a small class of this example:// A Common.Logging adapter that writes to the console, without the date and time. public class ConsoleLoggerFactoryAdapter : AbstractSimpleLoggerFactoryAdapter { public ConsoleLoggerFactoryAdapter() : base( Common.Logging.LogLevel.All, showDateTime: false, showLogName: true, showLevel: true, dateTimeFormat: null ) { } protected override ILog CreateLogger( string name, Common.Logging.LogLevel level, bool showLevel, bool showDateTime, bool showLogName, string dateTimeFormat ) => new ConsoleLogger( name, level, showLevel, showDateTime, showLogName, dateTimeFormat ); private sealed class ConsoleLogger : AbstractSimpleLogger { public ConsoleLogger( string name, Common.Logging.LogLevel level, bool showLevel, bool showDateTime, bool showLogName, string dateTimeFormat ) : base( name, level, showLevel, showDateTime, showLogName, dateTimeFormat ) { } protected override void WriteInternal( Common.Logging.LogLevel level, object message, Exception exception ) { var output = new StringBuilder(); this.FormatOutput( output, level, message, exception ); Console.WriteLine( output ); } } }
If you run your application, you should see the log in the console, for instance:
[DEBUG] LoggingCommonLogging.Greeter - Greeter.SayHello("world") | Starting.
Hello, world.
[DEBUG] LoggingCommonLogging.Greeter - Greeter.SayHello("world") | Succeeded.
See Also
Reference
Other Resources