Code Tips


Every application needs logging. It is, of course, especially helpful if you need to provide a user with just an apology message, but you need to store all kinds of data about the exception so that you can reproduce and debug it. Many people write their own because at its core, what you are doing it writing a string to a text file or saving a string to a database. However, to make that operation very robust, you need to do a lot of defensive coding around the operation.

This causes many people to turn to logging libraries like NLog. Quoting from their website, they indicate that NLog is able to do the following:

  • the ability to control the level of detail of our trace messages (such as displaying only warnings and errors or very detailed program trace)
  • the possibility of turning the tracing on and off for components of our proram separately, without turning the application off and recompiling it
  • writing trace messages to the file, system log, message queue or other output
  • being able to send particularly important messages by email or store them in a database
  • and others…

You can target your logs to go to a file, a console, email, a database, a message queue, event logs, pretty much anywhere that it would make sense for them to go. In addition, if you aren’t happy with the targets that NLog provides, you can write your own.

To get started with NLog, you can download it from here.

After you get it downloaded and extracted, you can either put the appropriate .dll (in my case I’m going to use NLog.dll v., labeled as NLog for .Net 2.0) in the GAC or store it somewhere that you put your shared .dlls so that you know where to go and reference it later. For this example, I’m just going to copy it right into my bin folder.

Create a new C# console application, named whatever you like. Add a reference to the NLog .dll and then add an application configuration file to your application (Right click on project–>Add–>New Item–>Application Configuration File). Put the following code into your application config file (app.config). All of the ${} stuff are just variables that NLog understands. They are all pretty straightforward and for a complete list, go see their website.

<?xml version="1.0" encoding="utf-8" ?>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>    
  <nlog xmlns=""
      <target name="console" xsi:type="Console" layout="${shortdate}|${level}|${message}" />
      <target name="file" xsi:type="File" layout="${longdate}|${stacktrace}|${message}" fileName="c:\Logs\${logger}.txt" />
      <logger name="*" minlevel="Debug" writeTo="console" />
      <logger name="*" minlevel="Error" writeTo="file" />

A small bit of explanation of the XML file. The targets section allows you to specify what kind of messages go to what kind of logging endpoint. The rules tell NLog where to go with certain types of messages, for instance, you can log Error to the file system, but just show debugging messages in the console.

Now, for the C# code. In your Program.cs, you can put the following code:

using NLog;

namespace NLogSample
    class Program
        private static Logger logger = LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
            logger.Debug("I won't go to the file, but I'll go to the screen");
            logger.Error("I'll do both.");

When you run this sample, you see this:

Output from our simple NLog Example

When I look in the log file, which I specified as c:\Logs\{name of logger, which is by default Namespace.Class}.txt, I find the following:

2008-07-29 10:43:45.8617|Program.Main|I'll do both.

That’s all there is to using NLog. As you can see, setting it up and using it is a snap and exposes much more functionality than common “roll your own” implementations. If you are doing web applications, the code from our app.config can go in the web.config and then you are all set to go.

We use NLog with my current employer and I couldn’t be happier with the results. If you don’t have a good logging framework in place, give NLog a try. Also, look around their site and give some of the other logging options a try.

One comment NLog

[…] choose the product that is named ‘n’ and then what you are doing” (remember my NLog and NUnit […]

Leave a Reply

Your email address will not be published. Required fields are marked *