NLog 101: Log Anything

2 minutes to read read

There are a plenty of logging tools and options in todays market but the userful are some. Almost all of them if not some do work on similar baseline, a set of rules to route and a sink to put in the logs. Some are really cool but have lost their sharpness with the low or no community updates like log4net which had been a great library for logging almost anything with .net. Some other good stuff like in the “Microsoft.Practices” namespace are also good but do have a good learning curve.

At this point NLog comes out as a wonderful logger with lowest learning curve, fastest adaption, small footprint, async support, and a large set of targets that can fulfill almost all requirement. With these set of articles, I shall try to put how easy it is to employe the hardlifting of logging in your projects. For this post, we shall take out lovely Simple Console Application. The download link for sample code can be found at the end of the post. Also note we are not using any abstract or patterns, this is just to demonstrate a brief purpose.

So, We first created the the Default Console Application Project with all default settings. And the we did a nuget install for nlog. This shall install the latest version of the package to project.

Install-Package NLog

Once we have this, we are pretty good to start. Second Step would be to add an app.config to project and define NLog Section. To do this, open app.config and add the following nlog section:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <nlog  xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
    <targets >
      <target name="ConsoleTarget"  xsi:type="ColoredConsole"  layout="${longdate}, ${level}, ${message}, ${exception}"  useDefaultRowHighlightingRules="true"/>
    </targets>
    <rules>
      <logger name="*" writeTo="ConsoleTarget" />
    </rules>
  </nlog>
</configuration>

This simple configuration change enables to log everything to Console. Please note that we have used ColoredConsole Target. which provides us colorful Logs on the console. List of available NLog Targets can be accessed here.

Ok, so lets fire and add some logs. In the Program.cs create an instance of NLog Logger.

    class Program
    {
        private static Logger logger;
        static void Main(string[] args)
        {
            logger = LogManager.GetCurrentClassLogger();
            logger.Trace("Logger Created");
            Console.ReadLine();

        }
    }

 

An the output can be seen as below:

console

Link to GIT: Source Code repo

Leave a Reply

Your email address will not be published.