Vaughan

Semantic logging with ASP.NET Core

.NET Core

One subtle adjustment that some of the older .net developers most probably need to make is that idea of semantic logging in ASP.NET core. This is subtle because a lot of us started used string interpolation a few years ago. The examples in the documentation look very similar to how my string interpolation strings look. See if you can spot the issue with below:


string name = John;
logger.LogInformation($"{name} has logged in.");

The information log will write out the text \'John has logged in.\' so even the log files will look good. This is missing the whole point of semantic logging though. The correct way to log it is:


string name = John;
logger.LogInformation("{name} has logged in.", name);

Now without the string interpolation, this is actually saves the log as a template with parameters. Your text log will look the same but if you are using some more complex log streams like Kibana, then you can start doing things like searching for the usage of the template irrespective of the parameters used. For example if you had two log lines.

John has logged in.
Peter has logged in.

Before semantic logging you would have to do some sort of wild card search on text. Now you can just search for the template {name} has logged in. to get both lines.

You are also able to search for parameters and in some cases do simple filtering. If your log template was:


string name = John;
int age = 30;
logger.LogInformation("{name} is {age}.", name, age);

You could also search for log lines where age < 30.

One small gotcha is that the parameters are applied in order and not by the name. So if you add the parameters in the wrong order then it will not match what you expect.

Related Posts

BMC logoBuy me a coffee