Adding extra metadata to a Microsoft "ILogger" LogDebug message?

307 views Asked by At

I have the following message I wish to log:

_logger.LogDebug("Finished: DB retrieved OutboundData settings.", new { ElapsedTime = stopwatch.Elapsed });
  • this is using the Microsoft.Extensions.Logging.ILogger interface
  • notice how there is no variables in the string message? this is by design.
  • notice how I've added some extra meta? this is to be added to the key/value stuff for the log message.

e.g.

enter image description here

see how this message has 4x extra key/values meta-data? That's awesome. I was hoping to add a 5th one ("ElapsedTime" / the actual value) to this single logging method.

Is this possible?

SIDE NOTE:

  • I'm using Serilog as the final logging library
  • Serilog is NOT any any of my projects except the host-project. So please do NOT suggest any serilog specific methods. That will not work.
1

There are 1 answers

4
ProgrammingLlama On

You need to create a scope to add all of your metadata to. For example:

using var scope = _logger.BeginScope(new Dictionary<string, object>() { ["ElapsedTime"] = stopwatch.Elapsed });
_logger.LogDebug("Finished: DB retrieved OutboundData settings.");