Create a Custom Trace Listener, Part 1

Visibility into components can be a real challenge in a web application. Often, there is functionality in a low level component that we need to trace because it is misbehaving or throwing a new error that it didn't before. Typically some kind of scaffolding needs to be created to put output somewhere so we can see it. This require work to be done in every component.

A better solution would be to have a lightweight tracing process that can be incorporated into a solution easily, preferably with minimal coding. Since this is such a universal need, Microsoft has provided a great means to do exactly this through built-in functionality in .NET.

.NET includes tracing capability out of the box in every component through the Debug.Trace function, which can write output into the Visual Studio IDE. This is nice for local development, but not much value when your component is running on a remote machine. Thankfully, .NET allows us to hijack the output of Debug.Trace and do anything we want with it.

Often in a framework, I will have many levels of components, and have a need to debug one small part of one component. Using a custom trace listener, I am able to put tracing informaion into a component, recompile it, and place it in the GAC on the server in question. Immediately, I get the trace output, regardless of where in the many layers of the framework it may live. This is a huge time savings--there is no need to develop custom functions to write or respond to the tracing output, and I have complete control over where the messages go.

Developing a custom trace listener will require the following:

1) Building a self-contained .dll that can be GACed which will consume the trace messages
2) Changing the web.config file of the application to tell it to use custom tracing


I take this a step further, and output the trace messages to a database, and check to see if a component's tracing setting is turned on or off. This allows for turning tracing on or off in an environment with no coding changes. But this requires a few more steps:

3) Set up a database to receive the test messages
4) Set up a mechanism to determine if an application's trace setting is on or off


Next time, I will discuss how to develop a custom trace listener and allow an application to use it. Then I will discuss the steps to turn this on and off in an environment.

0 comments:

Post a Comment