How to work with NLog in .Net

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

nlog

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. It's 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 high performant. Here's a nice documentation on NLog.

Getting started

First, you should download a copy of NLog.

You can install NLog using NuGet Package Manager also. 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. You can also install NLog using the Package Manager Console. Type in the following command in 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. Once you install this package, its related dependencies like, NLog and NLog.Schema are also installed and the NLog.dll assembly will be added to your project. You would also see a file called NLog.config added to your project. There would also be another file added to your project named NLog.xsd.

Creating a simple application using NLog

NLog provides support for the following type of log levels:

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

As an initial step, you'll first need to set up the name and path of the log file in the NLog.config file. Here's how you can do this:

<variable name="logFilePath" value="D:\NLog\IDG.log" />

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

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

Once the log file name and path has 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, i.e., whether in a file, a database or an event log, etc.

<rules>

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

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

</rules>

You can create a logger per class using the LogManager class in NLog library. Here's 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");

Here's 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();

        }

    }

}

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.