I'm a big fan of tracing in .NET and use it in every project I work on since it's a great way to find out why things aren't working properly. Tracing is especially useful when an application works in a test environment but not in production. My good buddy Michael Palermo recently wrote a nice post on how to dynamically grab the name of a method when using tracing which is a great idea. Mike's post made me think about a question I'm often asked: "How do you perform tracing in classes that don't have direct access to the ASP.NET TraceContext object?".
There are several potential answers to this question. Some or good and some are bad. You could pass a Page object instance to business object methods that need to write to the ASP.NET trace log but this would break some fundamental architecture principles so it's not something I'd recommend. You could also perform a trace operation in a business or data layer class by using the HttpContext class as shown next (you could used Michael's suggested technique to dynamically add the target method name into the message text):
While this works, using HttpContext ties the class where it's defined to the Web and makes it less useful in desktop or other non-Web applications (without checking to see if an HTTP context exists anyway). I'll admit that I use the HttpContext technique for demos since it's quick and easy, but for more enterprise applications there's a better technique that you might want to consider.
The System.Diagnostics namespace provides a Trace class that can be used to route data to the ASP.NET trace log exposed by viewing Trace.axd in the browser. You'll have to add some minor configuration code into web.config to get it to work, but it's quite simple. Here's an example of using the System.Diagnostics.Trace class's Write() method:
To enable trace messages created by classes used in an ASP.NET application to be written to the ASP.NET trace log, you can add the following code to web.config (add it outside of the system.web tag) which listens for trace operations and uses the System.Web.WebPageTraceListener class to write them to the trace log:
The value supplied to the type attribute should be placed on a single line in web.config of course.
By using the System.Diagnostics.Trace class (and related configuration code) with custom business or data classes you can use these classes with Web or desktop applications since the trace operations aren't tied to HttpContext any longer. Desktop applications would simply need to change the listener class in app.config to have trace operations written to a log file or other location. A class such as System.Diagnostics.TextWriterTraceListener could be used in this situation.