ASP.NET Logging to the Visual Studio Output Window with log4net

OK this one has been baffling me for a long time but I just ignored it. We have been using the open source logging library log4net for a long time, and for the most part it was working fine. But the one thing that I wanted to do but could never get working was logging to what my brain wanted to call “The Console,” AKA (to me) the Output window in Visual Studio.

I tried using the log4net appenders ConsoleAppender and ColoredConsoleAppender, to no avail. Turns out there’s a different appender that works with the Output window, and it’s not ConsoleAppender.

The appender in question is TraceAppender!

So here’s a little snippet of XML from my web.config files that handles output to the Output window (basically the same markup as appears on the log4net examples page):

  </log4net>
    <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p %c %m%n"/>
      </layout>
    </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="TraceAppender"/>
    </root>
  </log4net>

To those familiar with the way the log4net section looks in your web.config this will make sense, but the key concept is that, per the log4net documentation, “Events are written using the System.Diagnostics.Trace.Write(string,string) method” — and it turns out that one of the listeners is the Output window!

A colleague of mine and I were very confused by all this (I’m glad I wansn’t alone in that feeling either!), but we were both very glad to figure this one out.

Thanks go to Google (of course), and this post on the SharpDevelop forums.