January 17, 2011

Logging in ASP.NET Using Nlogger

Implementing NLog

1.)Download From  
  •  http://nlog-project.org/download.html 
  •  Download the …setup.exe file and execute it, it will also integrate itself into an existing installation of Visual Studio (2005 – 2010 including the free Express Editions!). 


2.) To Log Using  Nlog.NET, just right click on your project, choose “Add New Item”. Select the “Typical NLog Configuration File” from “MyTemplates” . This will write the log entries to a text file.



This will now add a new NLog.config file to your project and at the same time also add a reference to theLNog.dll .
This default config file is enough to write log entries. 



First, make sure that you change the “Copy to Output Directory” to “Copy always” in the File properties of the new config file. Otherwise this file won’t show up when you build your project. 
This will have  sections.
  1.  Targets 
  2.  Rules.

Targets defines where to write and how the log entry should look like (it can be a file, Database, event etc.) and how to write 

The Rules define what level of information to log and what target(s) shall be used. 

Both can be customized and configured. 
We can write multiple targets and multiples rules for different situations etc.

Sample log entry

Include Namspace

using NLog;


Object Creation


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



Sample Logging

Sample Logging on PageLoad with Different Error Levels
protected void Page_Load(object sender, EventArgs e)
    {
        logger.Info("Test Logging");
        logger.Warn("Test Logging");
        logger.Fatal("TestLoggin {0}", "In Default");
        logger.Log(LogLevel.Error, "Test Log");
    }



If we now run our project it will write a new log entry into the log.txt in the directory defined by the Target tag which is now "basedir" (Application Root  Folder)



No comments:

Post a Comment