Loggin’ Like Bunyan: An NLog Tutorial

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.

  1. 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.
  2. 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"
        <target name="logfile" xsi:type="File" fileName="log.txt" />
        <logger name="*" minlevel="Info" writeTo="logfile" />
  3. 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!

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

One thought on “Loggin’ Like Bunyan: An NLog Tutorial”

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: