joydip_kanjilal
Contributor

How to work with NLog in .NET

how-to
Nov 28, 20163 mins
Microsoft .NETSoftware Development

NLog can log your app data and create logs regardless of the size and complexity of your application.

NLog is an open source logging platform for use in .NET, Xamarin, and even Windows Phone applications. It is free, cross-platform, and easy to configure and extend. NLog is a great logging platform that is simple and comes with excellent support for log routing and management capabilities, making it a good choice when you have to choose a logging framework that is highly performant. 

Install NLog

First, you should download a copy of NLog.

Alternatively, you can install NLog using the NuGet Package Manager. To do this, all you need to do is create a project in Visual Studio, right-click on the project in the Solution Explorer window, and then select the “Manage NuGet Packages…” option. Next, you can select NLog.Config as the package you would want to install from the NuGet Package Manager window.

Or you can also install NLog using the Package Manager Console. Type the following command into the Package Manager Console and press enter.

Install-Package NLog.Config

To get started using NLog in Visual Studio 2015, you can install the NLog.Config package. When you install this package, its related dependencies including NLog and NLog.Schema will also be installed, and the NLog.dll assembly will be added to your project. You will also see two files added to your project, one named NLog.config and one named NLog.xsd.

NLog log levels

NLog provides support for the following log levels:

  • Trace
  • Debug
  • Info
  • Warn
  • Error
  • Fatal

NLog setup

You‘ll first need to set up the name and path of the log file in the NLog.config file. Here is how you can do this:

<variable name="logFilePath" value="D:NLogIDG.log" />

If you want to create a log file every day, you could specify the following in the variable tag instead:

<variable name="logFilePath" value="D:NLogIDG-${shortdate}.log" />

Specify a log target in NLog

Once the log file name and path have been specified, you should specify a log target. This can be done using the target tag in the NLog.config file:

<targets>
    <target name="logfile"
            xsi:type="File"
            fileName="${logFilePath}"
            layout="${longdate}   LEVEL=${level:upperCase=true}: ${message}"
            keepFileOpen="true" />
</targets>

Note that you can create multiple targets inside the targets tag.

You can also take advantage of rules to let NLog know where a particular log entry should be logged, whether in a file, a database, an event log, etc.

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

Create a logger in NLog

You can create a logger per class using the LogManager class in the NLog library. Here is how you can do it:

namespace Sample
{
  public class Test
  {
    private static Logger logger = LogManager.GetCurrentClassLogger();
  }
}

If you would like to retrieve a particular logger, you can take advantage of the GetLogger method of the LogManager class as shown below.

using NLog;
Logger logger = LogManager.GetLogger("SpecifyTheClassNameHere");

Simple NLog example in .NET

Here is the complete program for your reference that illustrates how NLog can be used to log data at different levels.

using NLog;
using System;
namespace IDGNLog
{
    class Program
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            logger.Trace("This is a trace message");
            logger.Debug("This is a debug message");
            logger.Info("This is an informational message");
            logger.Warn("This is a warning message");
            logger.Error("This is an error message");
            logger.Fatal("This is a fatal message");
            Console.ReadKey();
        }
    }
}
joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author