Integrating NLog with Visual Studio

Introduction

NLog is an open source logging framework that enables you to add high-quality logs and sophisticated tracing for your .NET application. It’s a free framework, cross-platform, and easy to configure and extend. NLog comes with excellent support for log routing and management capabilities. NLog can log your application data and create logs regardless of the size and complexity of your application.

Installing NLog

NLog is under the terms of the BSD license; that permits commercial usage with almost no obligation. NLog can be downloaded using the NuGet package manager from Microsoft Visual Studio. To install NLog from the NuGet Package manager console, use the following command.

Install-Package NLog.Config

A developer also can download NLog from this link.

What NLog Can Log

The following contextual information could be included in each NLog message:

  • Date and time of the generated exception
  • Log level
  • Source application
  • Stack trace information
  • Environment variable values
  • Details about the application exceptions
  • System/Machine, process, and so forth

Targets

By using NLog, a developer can write logs to the following targets:

  • A file
  • Console window
  • E-mail message
  • Database
  • Windows Event Log
  • Another machine on the same network
  • MSMQ
  • Others

Log Level

Each NLog tracing message is associated with a log level that describes its severity. It supports the following levels:

  • Trace: Very detailed log messages, required for tracing the source of the error
  • Debug: Debugging information of an application
  • Info: Informational messages
  • Warn: Warning messages from an application
  • Error: Error messages from an application
  • Fatal: Fatal error messages. Needs immediate attention

How to Create Log Messages

To create log messages from a .NET application, you need to use the Logger and LogManager classes present in the NLog namespace. Refer to the following code; this will create a Logger instance.

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

Sample Application

In following example, I will show you how to create application logs using the NLog library and how to write logs in the console window, log file, and e-mail.

Step 1

Open Visual Studio 2015. Create a New Console Application Project named NLogSampleApp.

New Console Project
Figure 1: New Console Project

Step 2

To install NLog from NuGet, Go to “Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution …”

Add NLog Framework to Project
Figure 2: Add NLog Framework to Project

Next, select the NLog.Config package and install from the NuGet Package Manager. Alternatively, you also can install NLog using the Package Manager console. Type in the following command in the Package Manager Console and press Enter:

Install-Package NLog.Config

Install NLog Config
Figure 3: Install NLog Config

Once you install this package, its related dependencies, such as NLog, NLog.xsd, and NLog.Schema also are installed. Additionally, the NLog.dll assembly will be added to your project.

NLog Config file
Figure 4: NLog Config file

Step 3

Now, write the following code in the Program.cs file and create a private static Logger object. I have used that object in my code for writing logs. Also, add NLog namespaces.

using NLog;
using NLog.Fluent;
class Program
   {
      private static Logger Mysameplelogger =
         LogManager.GetCurrentClassLogger();
      static void Main(string[] args)
      {
         LogSample();
      }

      static void LogSample()
      {

         Mysameplelogger.Trace("Trace: This is a sample Trace
            Log");
         Mysameplelogger.Debug("Debug: This is a sample Debug
            Log");
         Mysameplelogger.Info("Info: This is a sample Info Log");
         Mysameplelogger.Warn("Warn: This is a sample Warn Log");
         Mysameplelogger.Error("Error: This is a sample Error
            Log");
         Mysameplelogger.Fatal("Fatal: This is a sample Fatal Error
            Log");
         Mysameplelogger.Info()
            .Message("This is a test Info message '{0}'.",
               DateTime.Now.Ticks)
            .Property("Test", "InfoWrite")
            .Write();

      }
   }

Step 4

Next, open the Nlog.Config file and paste the following config code. Under the targets tag of the following example, I have added console, file, and e-mail as targets.

<targets>
   <target xsi_type="ColoredConsole" name="colored_console"/>
   <target name="console" xsi_type="Console"
      layout="${longdate}|${message}"/>
   <target name="file" xsi_type="File" fileName="D\logs\NLog.log"
      layout="${longdate}|${message}"/>
   <target name="sendMail" xsi_type="Mail"
      subject="Sample Application Log"
      to="XXXXXXXXXXXXXXXXXXXXXXXXXXX"
      from="XXXXXXXXXXXXXXXXXXXXXXXXX"
      body="${longdate}|${message}"
      enableSsl="true"
      smtpAuthentication="Basic"
      smtpServer="smtp.sampleemail.com"
      smtpUserName="XXXXXXXXXXXXXXXXXXXX"
      smtpPassword="XXXXXXXXXXXXXXXXXXXX"
      smtpPort="587"/>
</targets>
<rules>
   <logger name="*" minlevel="Error"
      writeTo="console,file,sendMail" />
   <logger name="*" minlevel="Trace"
      writeTo="colored_console"/>
</rules>

The following config section will set up the name and path of the log file in the NLog.config file. Each log message created from the code will be added in this file.

<target name="file" xsi_type="File" fileName="D\logs\NLog.log"
   layout="${longdate}|${message}"/>

For colored console output, I have used the following configuration settings:

<target xsi_type="ColoredConsole" name="colored_console"/>
<target name="console" xsi_type="Console"
   layout="${longdate}|${message}"/>

For sending e-mail, the following config section is written. I have used basic authentication with smtpusername and password.

<target name="sendMail" xsi_type="Mail"
        subject="Sample Application Log"
        to="XXXXXXXXXXXXXXXXXXXXXXXXXXX"
        from="XXXXXXXXXXXXXXXXXXXXXXXXX"
        body="${longdate}|${message}"
        enableSsl="true"
        smtpAuthentication="Basic"
        smtpServer="smtp.sampleemail.com"
        smtpUserName="XXXXXXXXXXXXXXXXXXXX"
        smtpPassword="XXXXXXXXXXXXXXXXXXXX"
        smtpPort="587"/>
</targets>

Step 5

Run the Console Application and you will see the output given in Figure 5.

Execution output
Figure 5: Execution output

To retrieve a particular logger, call the GetLogger method of the LogManager. Refer to the following example code:

Logger logger = LogManager.GetLogger("MentionTheClass");

Conclusion

I hope this example has given you the basic concepts about the NLog library. For more information about NLog, refer to this GitHub tutorial, published by the NLog team.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read