This article shows how to use PostSharp Logging and System.Diagnostics.Trace together.
Writing PostSharp Logging events to System.Diagnostics.Trace
To send PostSharp Logging events to Trace listeners:
Add PostSharp Logging to your codebase as described in Getting Started with PostSharp Logging.
Add the
PostSharp.Patterns.Diagnostics.Tracingpackage to your startup project.In the application startup method, include the following code:
LoggingServices.DefaultBackend = new TraceLoggingBackend();
Collecting Trace events into PostSharp Logging
If your source code already emits log events using System.Diagnostics.Trace, you can configure PostSharp Logging to collect log events directly emitted by System.Diagnostics.Trace, so that they are all processed by the same PostSharp backend and System.Diagnostics.Trace 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 System.Diagnostics.Trace and PostSharp like this:
// Add additional listeners:
Trace.Listeners.Add( new ConsoleTraceListener() );
// Configure PostSharp Logging to use Trace:
LoggingServices.DefaultBackend = new TraceLoggingBackend();
// Emit manual log records. Note that this logger skips PostSharp Logging, so indentation
// is not respected.
Trace.TraceError( "The {0} sky is shining {1}!", "blue", "bright" );
To collect Trace manual logging events into PostSharp, replace that startup code with the following:
// Add additional listeners:
Trace.Listeners.Add( new ConsoleTraceListener() );
// Then capture all trace listeners and remove them:
var listeners = TraceCollectingTraceListener.RedirectLoggingToPostSharp();
// Then create a PostSharp backend and pass the captured trace listeners to the backend:
LoggingServices.DefaultBackend = new TraceLoggingBackend( listeners );
You can now do standard Trace logging and the logging output will be collected and sent to PostSharp Logging:
Trace.TraceError( "The {0} sky is shining {1}!", "blue", "bright" );
When a logged method also writes a manual record, this record is indented like the records of PostSharp Logging:
App Error: 0 : TraceCollectingTraceListener | The blue sky is shining bright!
App Verbose: 0 : Greeter.SayHello("world") | Starting.
App Information: 0 : TraceCollectingTraceListener | Hello, world.
App Verbose: 0 : Greeter.SayHello("world") | Succeeded.
See Also
Reference
TraceLoggingBackend
TraceCollectingTraceListener
Other Resources