Sep 21

ASP.Net Logging Using NLog

My experience implementing logging on this site using NLog. It was very easy!

I should have been logging information and errors from day 1, but I guess its never too late to start. Based on Rob Conery's "endorsement", I chose to try NLog.

Step 1 was obviously to download the library. Then, I added the reference to NLog.dll in my web project and configured it. For configuration, NLog uses its own configuration file separate from Web.config and you don't have to do any modifications to Web.config at all. Below is my NLog.config, which is set up to log everything of level Info and above to the file specified (NLog.config goes in the root of the web app). As you can see, it is very straightforward to configure for your own needs:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <targets>
    <target name="console" xsi:type="ColoredConsole"
      layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
    <target name="file" xsi:type="File" fileName="${basedir}/Logs/rrLog.log"
      layout="${date}: ${message}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="file" />
  </rules>
</nlog>

After this, all that is left is to actually put in your log statements. So for example, to log all unhandled exceptions in your ASP.Net application, put the following in Global.asax.cs:

protected void Application_Error() {
   Exception lastException = Server.GetLastError();
   NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
   logger.Fatal(lastException);
}

And that's it! It can't be any easier than that, so I am pretty happy with NLog right now. I might checkout Log4Net sometime to make a comparison, but I don't have any reason to do so at this point. BTW, I recommend creating your own Logger service that wraps NLog so that you can easily switch to a different library if needed. I'll be doing that right now.

Tags:

Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top