Enterprise Library has been my go-to for logging for the past few years. This is largely because I’ve worked on a project that was using it, and it did what I needed. It was relatively easy to use, and I didn’t really have a reason to look elsewhere.
However, I was working on a new project that needed some logging, and I decided to explore some other options on a whim. Another team in the company was using NLog, so that’s where I went first. I gotta say, it seems a lot lighter weight and easier to use than Enterprise Library. It’s all available through NuGet, so adding it to any new project is a breeze.
Adding support for NLog to your application requires just two things: a reference to NLog.dll and an NLog.config file. Here’s how you can go from zero to logging in three steps.
- Install the “NLog Configuration” package from NuGet. This gives your project a reference to NLog.dll, the NLog schema (for Intellisense when editing NLog.config), and an empty NLog.config.
- Edit NLog.config to have a target and a rule. Here’s a very basic log-to-file config:
<?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="logfile" xsi:type="File" fileName="log.txt" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="logfile" /> </rules> </nlog>
- Get to loggin’! Create a Logger and use it.
var logger = LogManager.GetCurrentClassLogger(); logger.Info("Loggin' like Bunyan!");
It’s really that simple. The above config and logging code produce the following log entries:
2013-10-29 10:18:53.7819|INFO|NLogSample.Program|Loggin' like Bunyan!
One thought on “Loggin’ Like Bunyan: An NLog Tutorial”