Custom TraceListener writing trace messages to the .NET Services Service Bus


Dominick challenged me the other day...
For being able to better log information, warning and error messages in a truly distributed development, testing and operation environment, I built a sample custom TraceListener which leverages the Service Bus to pump tracing messages into the cloud.

Currently I am using the message-buffer-based volatile queuing mechanism in the Service Bus, but will move on to the Queue features introduced in the March 2009 bits soon.

There is a very simple ServiceContract I am using:

[ServiceContract(ConfigurationName = "Thinktecture.ServiceBusTraceListener")]
public interface IMessageTracing
{
    [OperationContract(IsOneWay = true)]
    void WriteMessage(string message);
}

All the magic is done in my custom TraceListener implementation. Here is a snippet of the relevant boilerplate code:

public class ServiceBusTraceListener : TraceListener
{
    ...
    
    public ServiceBusTraceListener()
        : base("Thinktecture.ServiceBusTraceListener")
    {
        CreateInMemoryQueue();
        SpawnWorkerThread();
    }

    ...

    public override void Write(string message)
    {
        WriteLine(message);
    }

    public override void WriteLine(string message)
    {
        traceMessagesQueue.Enqueue(message);
    }

    ...
}


This simple implementation uses a thread-safe in-memory queue data structure which is filled from within the TraceListener's WriteLine method. On 'the other side' of the queue there is a consuming thread which reads the messages from the queue (the in-memory one) and sends them to the Service Bus via a NetEventRelayBinding-enabled channel.
The background thread doing the Service Bus communication picks up all relevant WCF configuration from the config file (convention-based).

Download the sample solution.