Logging an exception and structured message data with ASP.NET 5

Once you started using ASP.NET 5 (aka. ASP.NET vNext), it’s surprisingly difficult to add a message that contains structured data to an exception. The LoggerExtensions either supports a flat message (which is probably good for a lot of cases), but it doesn’t support structured data for more sophisticated analysis.

Workaround

Let’s quickly look into a simple workaround, which is a 2-liner instead of a one-liner:

Solution

The logging extensions only support structured log messages when FormattedLogValues are provided, but don’t provide an interface to do the formatting behind the scenes. This is what I actually want to do:

I have created a pull request to the aspnet/Logging repository, but as of late October 2015, this wasn’t accepted. For the time being, you can simply copy/paste my changes to your project and start using the simplified logging capabilities.

Background

Why am I so obsessed with structured data in messages? Probably simply because I got used to it. I started using Elasticsearch as a logging sink over a year ago, and I mostly look into analyzing fields instead of full text messages. The detailed story is long, and probably worth a few posts, but it’s mostly around analyzing numeric data like performance data, or in the case of errors, by looking into categories of errors (outside of a hard to read error numbers).