Open sandboxFocusImprove this doc

Logging with System.Diagnostics.Trace

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:

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

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

  3. 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 the 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 will skip PostSharp Logging, so indentation
// will not be respected.
Trace.TraceError( "The {0} sky is shining {adverb}!", "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 {adverb}!", "blue", "bright" );

See Also

Reference

TraceLoggingBackend
TraceCollectingTraceListener
Other Resources

Collecting Logs from Other Frameworks