I now try and separate out my code into distinct layers. One problem with this is debugging the Business Layer through the web Presentation Layer. I though I had solved this by adding a reference to System.Web in my Business Layer and then grabbing a handle to System.Web.HttpContext.Current.Trace. I could then happily write debug information to my web page.
As I strive to achieve Zen Layer Separation (ZLS) I thought that this tied my Business Layer to my Presentation Layer too closely. So I took a look at System.Diagnostics. This Namespace has lovely built in tools for debugging your application, but I always thought it was more suited for desktop development. M$ was kind enough to make the Debug and Trace functions fully extensible through custom TraceListeners. So, in five minutes, I created the WebTraceListner.
public
class WebTraceListener : System.Diagnostics.TraceListener {
private static System.Web.TraceContext Trace = null;
public WebTraceListener() {
try { Trace = System.Web.HttpContext.Current.Trace; }
catch( Exception e ) {
throw new Exception( "WebTraceListener may only be used as part of an ASP.Net Web Application", e ); }
}
public
override void WriteLine( string Message ) {
Trace.Warn( Message );
}
//...Abbreviated for brevity
}
Now, debugging the Business Layer is as easy as System.Diagnostics.Debug("My debug messgage") and those messages are merrily routed to the ASP TraceContext for display on your page. The beauty of this is I could easily debug my Business Layer in a WinForm app by using the built-in TextWriterTraceListener instead of the WebTraceListner. I don't need to change any code at all, just a small change to the configuration file App.exe.config/Web.config. Instead of adding WebTraceListener in the section, you can add a listener that writes debug information to the console or a text file.
<
system.diagnostics>
<switches>
<add name="WebSwitch" value="4" />
--
0 = Off Output no tracing and debugging messages.
1 = Error Output error-handling messages.
2 = Warning Output warnings and error-handling messages.
3 = Info Output informational messages, warnings, and error-handling messages.
4 = Verbose Output all debugging and tracing messages.
--
>
switches>
<trace autoflush="false" indentsize="4">
<listeners>
<clear/>
<add name="WebTraceListener" type="Development.WebTraceListener,Development" />
listeners>
trace>
system.diagnostics>
Just one more step on the road to ZLS.
posted @ Friday, January 21, 2005 11:01 AM