A debug TRACE with a filter

There are a number of options for diagnostic tracing in .net. Today I really wanted to trace a very specific set of API calls that sent and received JSON. I just wanted the batches of JSON, not other ‘noise’. I had a quick look around and it looked like I just wanted to write;

Trace.WriteLine(myJson, "CategoryOfJson");

Problem is that is going to get swamped with all the other data. I had a look at source, switches, listeners, etc. In the end I decided to write this filtered listener;

public class JsonTraceListener : TextWriterTraceListener
{
    /// <summary>
    /// The filtered category
    /// </summary>
    public const string Category = "JSON";

    /// <summary>
    /// Initializes a new instance of the  class.
    /// </summary>
    /// The name of the file the  writes to.
    /// The name of the new instance.
    public JsonTraceListener(string fileName, string name)
        : base(fileName, name)
    {
    }

    /// <summary>
    /// WriteLine with category override will call this too, prefixed with the category text
    /// </summary>
    /// A message to write.
    public override void WriteLine(string message)
    {
        if (message.StartsWith(Category))
        {
            base.WriteLine(message);
        }
    }

    /// <summary>
    /// Writes a category name and a message to the listener you create when you implement the  class, followed by a line terminator.
    /// </summary>
    /// A message to write.
    /// A category name used to organize the output.
    public override void WriteLine(string message, string category)
    {
        if (category == Category)
        {
            base.WriteLine(message, category);
        }
    }
}

The listener just needs to be added and used;

var listener = new JsonTraceListener(@"C:\Logs\Json.log", "JsonListener");
listener.Filter = new EventTypeFilter(SourceLevels.All);
Trace.Listeners.Add(listener);
Trace.WriteLine("some json here", JsonTraceListener.Category);

// You must close or flush the trace to empty the output buffer.
Trace.Flush();

The code could be easily changed to allow any type of filter condition. I’m sure there is a nicer way to do this, feel free to comment.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s