英文:
Is it possible to pass some logging 'scope variables' to a .NET log message where these variables are not in the message?
问题
我希望向单个日志消息提供一些额外的元数据(也称为作用域变量)。
尽管日志消息没有与任何作用域变量的链接。那么我该如何做呢?
例如。
var userId = 1;
var userName = "Leia";
_logger.LogInformation("Saved user.");
那么如何将 userId
和 userName
传递给该日志消息,但我不希望在该日志消息文本中打印这些值。
因为我正在使用语义日志记录(在后台/日志记录器中),我可以轻松地查看与每条日志消息关联的所有元数据。
这可行吗?
英文:
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?
答案1
得分: 2
您可以尝试使用作用域。内置的日志记录基础结构和许多第三方日志记录提供程序使用此类似的抽象:
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");
输出消息:
{
"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
}
]
}
阅读更多:
英文:
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
-
Serilog Enrichment: The LogContext
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论