Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass some logging 'scope variables' to a .NET log message where these variables are not in the message?

I wish to provide some extra meta data (aka scope variables) to a single logging message.

The logging message doesn't have link to any of the scope variables though. So how can I do this?

for example.

var userId = 1;
var userName = "Leia";

_logger.LogInformation("Saved user.");

so how can I pass the userId and userName to that log message but i do NOT want to print those values in that log message text.

Because I'm using SEMANTIC LOGGING (behind the scenes/logger), I can easily see all the meta data associated to each log message.

Is this possible?

like image 884
Pure.Krome Avatar asked Feb 04 '26 04:02

Pure.Krome


1 Answers

You can try using scopes. Build-in logging infrastructure and many 3rd-party logger providers use this or similar abstraction:

var services = new ServiceCollection();
services.AddLogging(builder => builder.AddJsonConsole(opts => opts.IncludeScopes = true));
var sp = services.BuildServiceProvider();
var logger = sp.GetRequiredService<ILogger<Tests>>();
using var _ = logger.BeginScope(new Dictionary<string, object>
{
    { "ScopedId", 1 }
});
logger.LogError("Test");

Output message:

{
   "EventId":0,
   "LogLevel":"Error",
   "Category":"NET7Tests.Tests",
   "Message":"Test",
   "State":{
      "Message":"Test",
      "{OriginalFormat}":"Test"
   },
   "Scopes":[
      {
         "Message":"System.Collections.Generic.Dictionary\u00602[System.String,System.Object]",
         "ScopedId":1
      }
   ]
}

Read more:

  • Log scopes from official docs
  • The semantics of ILogger.BeginScope()
  • Serilog Enrichment: The LogContext
like image 171
Guru Stron Avatar answered Feb 05 '26 16:02

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!