After messing around with my own logging engine (boo!) I decided to play around with NLog, it looked much simpler to use and configure than log4net (not that log4net looked all that complicated, just that NLog seemed cleaner to me).
So grab the NLog setup package from SourceForge and install it. So that’s it. Yes, that simple really, the installer includes a series of templates that will be used later to create an empty configuration file.
I like using the Datestamp of YYYYMMDD_HHMM so 1:30 PM on April 1st, 1980 would be 19800401_1330. This is the configuration I used in the Nlog.config file to write the timestamp’ed log data to a text file (add a new file to your project and pick the ‘Empty NLog Configuration File” from the My templates section), this setup will also create a Datestamp on the log file:
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <target name="file" xsi:type="File" fileName="${basedir}/${date:format=yyyyMMhh}.log.txt" layout="${date:format=yyyyMMhh_HHmm}|${level}|${stacktrace}|${message}"/> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="file"/> </rules> </nlog>
Here is a example of using the logging:
using System; using System.Collections.Generic; using System.Text; using NLog; namespace NlogTester { class Program { private static Logger _logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { _logger.Trace("This is a Trace message"); _logger.Debug("This is a Debug message"); _logger.Info("This is an Info message"); _logger.Warn("This is a Warn message"); _logger.Error("This is an Error message"); _logger.Fatal("This is a Fatal error message"); Console.ReadKey(); } } }
This creates an excellent log file that looks like this:
20080109_2136|Trace|AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main|This is a Trace message 20080109_2136|Debug|AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main|This is a Debug message 20080109_2136|Info|AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main|This is an Info message 20080109_2136|Warn|AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main|This is a Warn message 20080109_2136|Error|AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main|This is an Error message 20080109_2136|Fatal|AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main|This is a Fatal error message
Good stuff indeed.
Enjoy!