NLog to provide custom tracing for your ASP.NET

Posted By: Ajay Saptaputre, 15 Oct,2015 Total View : 2310
submit to reddit

In my previous article I discussed about CRUD Operations Using MVCContrib Grid with ASP.NET MVC 5 and Entity Framework 6 and CRUD Operations Using NHibernate with ASP.NET MVC 5 and Export To Excel From WebGrid In ASP.NET MVC5 and Entity Framework 6 and How Email Can be Used to Track User IP address Using ASP.NET

What is NLog?

In this article I am going to discuss about NLog, NLog is a free logging platform for .NET or .NET library, which enables you to add sophisticated tracing code to your application. NLog makes developer's life easy to produce and write high-quality logs for your application regardless of its size or complexity and much, much more. In this article I will explain ASP.NET example using NLog.

NLog Features

  • Easy configuration - NLog is very easy to configure, without restarting the application you can configuration can be changed.
  • Templatable - Every log message can be templated with various layout renders
  • Extensible - Even though NLog has built in targets, it allows you to write custom targets or pass custom values

NLog Targets

  • Files - You can write logs to file, NLog will not lock your file by default.
  • Event Log - You can write logs to event log local or remote.
  • Database - You can write logs in databases supported by .NET
  • Console - You can write logs to the command-line console with colorful messages.
  • E-mail - You can send emails whenever application errors occur.
  • ASP.NET trace - You can write logs to the built in trace in ASP.NET.

NLog Installing

In order to use NLog, you simply need to install NLog.Config package and this will automatically install NLog and NLog.Schema packages. NLog is open source and available at available on GitHub or NLog library also available at NuGet, you can easily download. You can right click on your Visual Studio project and select "Manage NuGet Packages", search "NLog" and click on "Add" from result list or search "NLog.Config package" and install or you can use following command in the Package Manager Console:

Install-Package NLog <version>

NLog Configuration

In order to use NLog, you need to open the web.config/NLog.config file and add some logging rules: In the <targets> section, add:
<target name="dailyFile" xsi:type="File" layout="${longdate}

The above code snippet defines target with name "dailyFile". Also setting other attributes like "fileName", "archiveFileName", "maxArchiveFiles" and "keepFileOpen" which will send logs to a file named "ErrorLog-.log" at application root folder, similarly archiveFileName.

In the <rules> section, add:

  <logger name="*" minlevel="Error" writeTo="dailyFile" />

The above code snippet will direct all logs (name="*") for error level (some other levels are Info, Warn, Error and Fatal) to a target named log file.

NLog Creating Loggers

In order to create NLog to start writing logger, you need to add namespace in your class file and use "LogManager to create logger instance. NLog is belonging to "NLog" namespace. As per good practice, create one logger per class. This will create a Logger instance with the same name of the class.

using NLog;

namespace MyNamespace
  public class MyClass
	static Logger logger = LogManager.GetCurrentClassLogger();
	logger.Error("Error message: " + Message + " Stack Trace: " + StackTrace);

Log Levels

Based on importance of log messages, you can route log messages using logger name and log level. NLog supports various log levels:
  • Trace - This level is typically used during development. Because it includes high-volume information.
  • Debug - This level is also used during development to log debugging information, typically used in production environment.
  • Info - This level is typically used in production environment.
  • Warn - This level is used to log warning messages, which are temporary failures.
  • Error - This level is used to log error messages, typically Exceptions.
  • Fatal - This level is used to log very serious errors.

NLog Writing Log Messages

As mentioned before, there are six different log levels whose names correspond to log levels: Trace(), Debug(), Info(), Warn(), Error() and Fatal(). To emit log message, call one of its method on the Logger. There is another method you can use, called Log() which takes log level as a parameter.

NLog Error Log

When you run the application, in page load, it will throw exception and in exception block exceptions are logging into error log. See below code snippet:

using System;
using NLog;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
    private static Logger logger = LogManager.GetCurrentClassLogger();
    protected void Page_Load(object sender, EventArgs e)
            int a = 0;
            int b = 0;
            int c = 0;
            c = a / b;
        catch (Exception ex)
            //Considering all types of exception
           logger.Error("Error message: " + ex.Message + 
		   " Stack Trace: " + ex.StackTrace);

Log File

If you open log file, you can easily find all exception are logged into the log file.

Download Code ⇩

Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...

submit to reddit
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Google MAP API V3
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
Protected by Copyscape Original Content Checker
Copyright ©2017 Unauthorized reproduction/replication of any part of this site is prohibited.