Sunday, March 11, 2012

ASP.NET MVC 3, Tracing, and Log4Net AspNetTraceAppender

I set up a ASP.NET MVC 3 application that uses log4net as the logging infrastructure.  It is convenient to be able to view logging information on the page I am working on, as opposed to having to switch back and forth between browsers and log files.  In Web Forms applications I accomplished this by configuring log4net to use the AspNetTraceAppender  and enabled tracing in the web.config which would display logging information as part of the trace diagnostics information.  However, this does not work in MVC as it seems to use a different tracing infrastructure.  From http://stackoverflow.com/questions/3328678/asp-net-mvc-tracing-issues quoting "MVC 2 in action":

When you called Trace.Write() in Web Forms, you were interacting with the Trace- Context class. This exists on your ViewPage in ASP.NET MVC, but this isn’t where you would want to write tracing statements. By the time you’ve passed the baton over to the view, there’s no logic there that you’d need to trace. Instead, you’d like to trace the logic embedded in your controllers. You might try to leverage the TraceContext class in your controller, but these statements won’t ever make their way to the list of messages in the trace log (on your page or on Trace.axd). Instead, you can use System.Diagnostics.Trace and set up your own TraceListeners to inspect the activity in your controllers. Alternatively, you can leverage a more mature logging framework such as log4net or NLog:
You debug ASP.NET MVC applications just as you would any .NET application. Tracing, however, doesn’t offer as much for MVC. Instead, you can lean on the built-in TraceListeners in .NET, or utilize a good logging library like those mentioned earlier. Another aspect of error logging is health monitoring.
Per the stackoverflow post, I installed glimpse .  With tracing enabled in the web.config, glimpse running, and the AspNetTraceAppender configured everything worked; my log messages were displayed in the browser!

No comments:

Post a Comment