|||

Simple logging with NLog Application logger

If you are like me and you rely on trace information generated by your programs to diagnose production issues then you might like NLog. NLog is a lightweight open source logging library which has worked well for me in the last couple of projects that I have shipped. Amongst many different configuration options that NLog offers, the 2 that I have used mostly are Console logging and Flat text file logging. To get started you can download the msi from the downloads page. The Complete” option of the installer would install the core library dlls along with the necessary documentation under your program files. The main reason for using the msi is that it integrates NLog with Visual Studio and provides intellisense when you are adding/editing Nlog related stuff in you Web.config or App.config. The installer would also register the NLog dlls in the GAC, so that they are accessible for referencing when you right click on your project.

sc

Once the reference is setup, you have to add NLog as a custom configuration section in Web/App.config file as follows:

<configuration>
<configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
    <nlog
        xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true">
        <variable name="LogFileName" value="App"/>
        <variable name="LogFileExtension" value="log"/>
        <variable name="LogsLocation" value="c:\TempFiles\AppLogs" />
        <targets async="true">
            <target name="console" xsi:type="Console" />
            <target name="flatFileTarget" xsi:type="File"
              layout="${date:format=dd-MM-yyyy HH\:mm\:ss.fff} | ${message}"
              fileName="${LogsLocation}\${LogFileName}.${LogFileExtension}" 
              archiveFileName="${LogsLocation}\${LogFileName}.{#####}.${LogFileExtension}" 
              archiveAboveSize="500000" maxArchiveFiles="10" 
              archiveNumbering="Rolling" 
              createDirs="true" 
              concurrentWrites="true" 
              archiveEvery="Day" 
              deleteOldFileOnStartup="true" />
        </targets>
        <rules>
            <logger name="*" writeTo="flatFileTarget" />
            <logger name="*" writeTo="console" />
        </rules>
    </nlog>
</configuration>

Couple of things worth noting here are:

  1. You can declare variables for values that are used repetitively in your configuration and thus makes it more maintainable.
  2. You can group one or more log targets under the tags and you can make all logging asynchronous just be adding the asyn=”true” attribute. Therefore any logging wouldn’t impact app performance.
  3. You can achieve log files when the size of them gets above archiveAboveSize and also you can define the maximum number of archive files by maxArchiveFiles attribute.

Finally, add the following code in a utility class or whatever location suits your coding style and you have a full fledged logging system ready for your app.

class Program
{
    static void Main(string[] args)
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        logger.Log(LogLevel.Debug, "Test");

        Console.Read();
    }
}

and when i run my app i see the same output in a console window and a flat file named App.log under c:


Up next SVN Externals — Share common assembly code between solutions A simple image carousel prototype using Asp.net webforms and SignalR
Latest posts Refactor react code to use state store instead of multiple useState hooks Notes on Python Threat Modelling - Using Microsoft STRIDE Model WCAG - Notes Flutter CI/CD with Azure Devops & Firebase - iOS - Part 1 Flutter CI/CD with Azure Devops & Firebase - Android - Part 2 How to samples with AWS CDK A hashicorp packer project to provision an AWS AMI with node, pm2 & mongodb Some notes on Zeebe (A scalable process orchestrator) Docker-Compose in AWS ECS with EFS volume mounts Domain Driven Design Core Principles Apple Push Notifications With Amazon SNS AWS VPC Notes Building and Deploying apps using VSTS and HockeyApp - Part 3 : Windows Phone Building and Deploying apps using VSTS and HockeyApp - Part 2 : Android Building and Deploying apps using VSTS and HockeyApp - Part 1 : iOS How I diagnosed High CPU usage using Windbg WCF service NETBIOS name resolution woes The troublesome Git-Svn Marriage GTD (Getting things done) — A simplified view Javascript Refresher Sharing common connection strings between projects A simple image carousel prototype using Asp.net webforms and SignalR Simple logging with NLog Application logger SVN Externals — Share common assembly code between solutions Simple async in .net 2.0 & Winforms Clean sources Plus Console 2 — A tabbed console window