Structured Logging comes to NLog

NLog 4.5 (now in alpha status) makes it significantly easier to filter, correlate, and analyze large volumes of log data from complex, asynchronous and distributed systems.

Along with plain format strings, NLog can now accept message templates that not only describe an event, but capture the data associated with it as first-class properties:

var logger = LogManager.GetCurrentClassLogger();

logger.Info("Setting flow to {Rate} L/s for {Duration} s", flow, duration.TotalSeconds);  
// -> Setting flow to 300 L/s for 10 s
// ->   Rate = 300
// ->   Duration = 10

Log events that use message templates can be rendered out to the terminal or a log file, where they appear with formatted messages just like other text logs:

2017-02-13 16:29:57.4139|INFO|Example.Program|Setting flow to 300 L/s for 10 s  

This is great for ergonomics at development time, but in production it's more common to collect structured log events in a format such as JSON, which makes it easy to access the properties associated with the event like Rate and Duration in the example.

{"@t":"2017-02-13T06:29:57.4139Z","Rate":300,"Duration":10,"@m":"Setting flow to 300 L/s for 10 s"}

Using the new NLog.Targets.Seq package, events can be centrally collected over HTTP and displayed with full-fidelity in the Seq interface:

Flow event example

Here the power of structured logging is obvious: finding events with a total output greater than 100 kL is trivial compared with the effort we'd expend hacking through plain-text logs with regular expressions.

There are other subtle benefits to structured logging that you might not expect. Notice the filter on the right-hand side of the screenshot above? By filtering down on the message template we can view all events generated from the example logging statement by type, unambiguously selecting just the events we're interested in.

What else is great about structured logging in NLog 4.5? It works alongside all of the existing NLog functionality, so you can incrementally introduce it into your applications without having to immediately convert the logging statements you've already written.

NLog.Targets.Seq package is a brand new package that's written especially for NLog 4.5+. We'll be updating and improving it as NLog 4.5 progresses from alpha to RTM, and we'd love to have your feedback on it as we go.

Happy logging!


Read more posts by this author.