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?
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:
ILogger.BeginScope()If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With