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.
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:
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: