Walkthrough: Creating a Custom Trace Listener

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

This walkthrough demonstrates how to create a custom trace listener for use with the Logging Application Block.

To reproduce the demonstration

  1. Add a new class named DebugTraceListener to your project.

  2. Specify that the class derives from CustomTraceListener.

  3. Add the class attribute ConfigurationElementType. Specify the type CustomTraceListenerData as the attribute parameter.

    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class DebugTraceListener : CustomTraceListener
    
    'Usage
    <ConfigurationElementType(GetType(CustomTraceListenerData))> _
    Public Class DebugTraceListener
      Inherits CustomTraceListener
    
  4. Add the TraceData method to your class, and then implement the behavior required when logging to your custom trace listener.

    public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
    {
      if (data is LogEntry && this.Formatter != null) 
      {
        this.WriteLine(this.Formatter.Format(data as LogEntry));
      }
      else
      {
        this.WriteLine(data.ToString());
      }
    }
    
    'Usage
    Public Overrides Sub TraceData(ByVal eventCache As TraceEventCache, ByVal source As String, _
           ByVal eventType As TraceEventType, ByVal id As Integer, ByVal data As Object)
      If (TypeOf data Is LogEntry) And Me.Formatter IsNot Nothing Then
        WriteLine(Me.Formatter.Format(DirectCast(data, LogEntry)))
      Else
        WriteLine(data.ToString())
      End If
    End Sub
    
  5. Override the Write and WriteLine methods to implement the behavior required when logging to your custom trace listener.

    public override void Write(string message)
    {
      Debug.Write(message);
    }
    
    public override void WriteLine(string message)
    {
      Debug.WriteLine(message);
    }
    
    'Usage
    Public Overrides Sub Write(ByVal message As String)
      Debug.Write(message)
    End Sub
    
    Public Overrides Sub WriteLine(ByVal message As String)
      Debug.WriteLine(message)
    End Sub
    
  6. Configure the application to use the Logging Application Block.

  7. In the Enterprise Library configuration tools, configure a new custom trace listener.

  8. Specify DebugTraceListener as the type name.

  9. Create or modify existing categories to use the custom trace listener.