How to replace this code:
string name = "John";
logger.Information("length of name '{name}' is {nameLength}", name, name.Length);
with C# String interpolation like this or similar
string name = "John";
// :-( lost benefit of structured logging: property names not passed to logger
logger.Information($"length of name '{name}' is {name.Length}");
but keep the property names for structured logging to work?
Benefits would be:
- Increased readability
- You'll never forget an argument in arguments list or a property name in message template, especially when you make changes to your logging code
- You always know what this property name will print to your log
Add this file to your project. It has
ILogger
extension methodsVerboseInterpolated()
,DebugInterpolated()
and so on. There are also unit tests here.Usage with format string
But be careful: it's all too easy to use the wrong method. If you accidentally use the Serilog's method, for example
logger.Debug($"length = {length:propertyNameForLogger}")
, it will loglength = propertyNameForLogger
, so no argument value will be logged. This is due topropertyNameForLogger
is format for your value.Usage with anonymous types