最近,我配置了Serilog来很好地使用ASP.NET Core2MVC应用程序,下一项任务是在系统的每一层跟踪传入web应用程序的请求。因此,基本上,我们希望传播一些令牌(如Serilog生成的RequestId到较低的应用层)。
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.RollingFile" ],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning"
}
},
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"pathFormat": "log-{Hour}.txt",
"fileSizeLimitBytes": "",
"retainedFileCountLimit": "",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Application}] [{Level}] [{RequestId}] - {Message}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "MultilayerApp"
}
},在日志中,我们有很好的输入,比如
2018-01-19 14:06:01.165 +00:00 [App] [Warning] [0HLAV6PIMA9M0:00000001] - Accessing expired session, Key:"6e7f3ab5-db62-335d-1bc7-6824e5b918f5"但我的问题是,在Serilog中,RequestId的实现在哪里更丰富?老实说,我找不到。
发布于 2018-02-05 23:46:26
在ASP.NET核心中,某些记录器公开的RequestId是TraceIdentifier在HttpContext上的值。可以在整个应用程序中使用此属性来标识当前请求。
但是,出于日志记录的目的,回退到HttpContext不是一种可行的方法。Microsoft.Extensions.Logging抽象支持logging scopes,这是一种向应用于该作用域的记录器提供附加信息的方法。
默认情况下,ASP.NET核心会打开两个日志记录范围。其中之一是打开at the beginning of every request的HostingLogScope (如果至少启用了关键日志记录)。
日志记录器可以通过实现BeginScope method来访问信息,该at在每次请求开始时将HostingLogScope对象传递给它,并简单地迭代该对象,直到找到该属性:
string requestId = null;
if (state is IEnumerable<KeyValuePair<string, object>> properties)
{
foreach (var property in properties)
{
if (property.Key == "RequestId")
{
requestId = property.Value as string;
}
}
}Serilog does pretty much the same,但存储所有属性in the log event。这就是为什么您找不到对RequestId的显式引用的原因,但是当您指定包含它的日志字符串格式时,它仍然存在。
https://stackoverflow.com/questions/48625624
复制相似问题