NLog.. The awesome logging tool for .NET that don’t quit

 

What is NLog?

NLog is a logging tool for any .NET application out there that you can think of. Web Services, ASP.NET Web Forms / MVC, Windows Services, WPF applications etc.. You name it, they log itSmile.  NLog takes the confusion of handling your own file locks and settings for logging levels and migrates it into it’s own configuration files and libraries. All the things that used to take hours of coding is now hidden so you the programmer no longer has to worry about it.  I have been using this revolutionary tool for a little over 2 years now and have had no problems with it. The only caveat is that the IntelliSense and templates are not supported in VS2012. In this tutorial, I will show you how to use NLog in both VS 2010 and 2012.

Installing NLog

This step is done for both VS 2010 and 2012. Download the installer on codeplex or from the Nlog website: http://nlog.codeplex.com/downloads/get/259960. Once Downloaded, all of the defaults are fine. There is no need to do any advanced installation at this point. Once installed, you can move on to the next step for VS 2010

Using NLog on VS2010

Adding the NLog Template

VS 2010 is the newest Visual Studio that NLog currently supports for IntelliSense and templates. This is not to say that NLog is not supported or that they aren’t working towards supporting such features. In fact, NLog has been placed on NuGet, so there is definitely still a lot of support for it.

With that said, the first thing you want to do after Creating a project in Visual Studio is adding the NLog Template. To do this, Right click the project and select Add->New Item.

image

Then, under the Installed Templates, select NLog-> Empty NLog Configuration File. Use the default name of NLog.config.

image

After selecting the Add button, you will notice a few things. First, there will be a reference to the NLog libraries in your project. Second, there will be a NLog.config file that is really an xml file. At this point, you are almost ready to start logging!! There are just a few more things to set, but remember, once it’s set, you can forget Smile!!

 

Setting up the configuration file

The first thing you should do to save lots of heat ache and banging your head against the wall is set the NLog.config file to Copy always. Why you say? Because under certain circumstances, VS does it for you and certain curcumstances it does not. I have been caught several times spending hours in security settings wondering why the hell my logging isn’t working. Well more often than not, it was because of the configuration file not being in the release or debug folder when I copy or publish it. Not sure who’s fault it is, but whoever you are.. I hate you!@!

You may be wondering, how does one do such a magical thing like set a file to Copy always to the current folder. Well, here you go:

image

Based on the diagram above, Select the NLog.config file and look at it’s properties. This can be different depending on your set up, but  if you right click the file, you can select Properties from the menu. Once in the Properties, you may notice it says “Do not copy” Change it to “Copy always” and save. This will prevent issues in the future.

The configuration I use the most is shown here:

<?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">

  <!-- make sure to set 'Copy To Output Directory' option for this file -->
  <!-- go to http://nlog-project.org/wiki/Configuration_file for more information -->

  <targets>
    <target
      name="logfile"
      xsi:type="File"
      fileName="${basedir}/Logs/debug.txt"
      archiveEvery="Hour"/>
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="logfile" />
  </rules>
</nlog>

 

This configuration will log to the root of where the application is running ( This can get tricky if you are not careful with Web Services.. more on this later). The configuration also tells NLog to log every hour. I do that as a test, but is probably overkill for most applications. Usually you will use Day or a certain size constraint.

The last import piece is the “minlevel”. This tells NLog at what level you wish to log at. This allows your to have levels of logging out of the box. In this case, because I pulled this from a debug application environment, I have it set to Info. Most often you will want this set to Info or Debug in debug mode and Error in release mode. If you do this, any Info or Debug tagged logging will be passed over in release mode for a faster environment for your users.This will allow you to have the minimum logging in production while still having logging that you can turn on in a flash. Why in a flash you might ask? Simple, the power of xml configuration files.

When using these xml settings files, you can easily make the change in production for the minlevel to be Info and bam, you get logging at the Error and Info levels. This is great for things that seem to appear in production but not in development. Things like App pool misconfigurations, Security/ permissions issues etc.. So with all that, you may say, ok, lets start coding… Not yet kimosabe..

Settings NLog up with Visual Studio 2012

So I thought I would go through the process of setting things up in VS 2012 before going through the action. If you will not be using VS2012 at all, then please feel free to skip this part and move on to the main event.

VS 2012 currently has no support for NLog in the sense that it does not have IntelliSense even if you add the XML schemas from 2010 to 2012. I tried. If anyone knows how to manually add this and the templates, by all means, post the answer here! I am always up to learn something new. Until then, here is the solution.

Once in a new project, open Package Manager to get NLog via NuGet. To Do this, Click Tools –> Library Package Manager –> Package Manager Console as shown below:

image

A new window will appear that looks like a command prompt… guess what.. it is! This is where you can download thousands of NuGet plugins and features for Visual Studio. I’d love to talk about how awesome NuGet has the potential to be, but I don’t have enough hours in the day. Soooo, from The command prompt you should see a PM>.  This means the console is waiting for your response. Type the following: Install-Package NLog. This will install the various libraries required for this application to use NLog. Now, You want to Right Click the project and select Add->New Item like you did above for the template only this time Select Data->XML file. Before selecting Add, Change the name of the file to NLog.config. This will act the same as the configuration file from the template. Now when the file has been created, Copy and paste the code I provided in the configuration example above into this file and save. The only remaining thing to do is Change the file to Copy Always as shown below.

image

 

Ok.. So Gregg, how does one use this tool you say is awesome?

Great question. So now we have set everything up in either enviornment and want to start using NLog. So lets get started.

First thing you want to do is add the NLog using (if in C#). Once this is done, the most comon practice is to use a global private variable called logger. This has become so widely known because you can type nlogger, tab, tab and it will use an installed snippet to finish it for you. (This is only in VS2010 currently). If you don’t have VS2010, the syntax is like so:

private static Logger logger = NLog.LogManager.GetCurrentClassLogger();

This will create a logger instance and you can use this throughout your code ( if it is set global) and log each time you reference it. Here is an example of using the logger for different scenarios:

 

public void GetCoolData(string dataToConvert)
{

    logger.Info("Callers Parameters: " + dataToConvert);

try
{
    Do Cool Data Stuff...
}

catch(Exception ex)
{
logger.Error(ex);
}

}

As you will notice above, there are two times logger is being referenced. The first is just going to concatenate the string text and the parameter filled out by the caller of the method. If your minlevel for the configuration file is set to error, this log will not occur nor will it take any CPU time to analyze it. The second logging instance is of an exception that gets caught. This will log out the whole stack message and allow you to capture all that info in one fail swoop and then continue on your merry way or give the user some nice little message.

Pretty neato huh?

There are lots of things you can do with NLog including various rules and targets within the configuration file. You can go look through the various options on their documentation website. http://nlog-project.org/wiki/Documentation has great documentation on how to use it.You can event use SlowCheetah, the XML Transformation VS tool to have on the fly environments for NLog.

So you mentioned Web Services as a potential issue? What up with that?

Well, technically, I didn’t say it was an issue, you just have to be careful. But that goes for any custom settings file you use on a web service. Especially when you come from the windows application or windows services world. This is because normally, in these worlds, wherever your .exe file is, that’s your $base or root if you will of where an application starts it’s life cycle. In a Web Application or Web Service, this is a bit different. In either of these applications, the root is actually C:\Windows\SysWOW64\inetsrv. This is where IIS and asp.net executable lives, so this is where web services and web applications start.

 

With this said, NLog seems to take care of this, but I have heard of people having issues with this in the past, so it is worth mentioning not only for this tool, but in general!!

 

As always, Happy Programming

Advertisements

About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in ASP.NET, C#, logging, MVC, Programming, WCF, XML, XML Transforms and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s