Configure NLog to Log Application-Specific Data

NLog is one of my favorite .NET loggers. It has a bunch of great features, is easy to configure via a config file or programmatically, and is very extensible. Recently I had a customer who wanted to improve the logging in their web-based application. They wanted to log to a database, since that was what they had been doing successfully, and they wanted to be able to easily store the associated customer with the log data. But they didn’t want to have to add it to every message, or rewrite the logging interface to accept a customer id parameter. What’s more, the customer id wasn’t stored in any central location for a given thread or web request, so in this case we couldn’t take advantage of NLog’s support for grabbing fields from ASP.NET containers (session, cookie, HttpContext, etc.). We were able to get what we needed working quickly, using the steps shown below.

Create a Custom Logger

Since we didn’t want to have to pass the customer id with every log message, and we couldn’t store it somewhere centrally where NLog could access it, we opted to subclass Logger and add the value to the MappedDiagnosticsContext, which exists for this purpose:

Use the Custom Logger in the Application

Next, we needed to access the custom logger anywhere in the application where we would be performing logging. We wanted to keep NLog’s default convention of using a named logger per class, which would allow us to easily query the log output for information related to a particular class. Below is a sample class showing how to get the logger, set its customer ID (used by all subsequent log methods), and log a message:

Configuring NLog in Code

NLog supports both config-file based configuration as well as code-based configuration. You can use whichever you prefer. In this case, I opted for code-based, since it provides a little greater transparency and error-catching than XML does, in my experience. The NLog docs don’t show an example of API-based configuration of a database target, so here is what that looks like if you need it. Note that the custom field we’re capturing, customerId, is mapped in targets using the ${mdc:item=KEY} syntax. You can see this used in both the consoleTarget and the databaseTarget shown below:

Bringing it all Together

All that’s left is to create the table and add the connection string (named “NLog” in the example above) to your application’s config file. You’ll find the complete, runnable sample, including the script to create the database table, on GitHub. Here’s an example of what the output looks like, including the application-specific column:

Sample Data

Next: Configure NLog Using StructureMap (without losing access to the richness of its API)