最近我配置了Serilog以与ASP.NET Core 2 MVC应用程序配合使用,接下来的任务是在系统的每一层上跟踪传入的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
richher?老实说,我找不到它。
在ASP.NET Core中,一些记录器暴露的RequestId
是TraceIdentifier
上HttpContext
的值。可以在整个应用程序中使用此属性来标识当前请求。
为了记录目的,回到HttpContext
是不可行的方式。 Microsoft.Extensions.Logging
抽象支持logging scopes,这是一种为在该范围内应用的记录器提供附加信息的方法。
默认情况下,ASP.NET Core会打开两个日志记录范围。其中之一是打开HostingLogScope
的at the beginning of every request(如果启用了至少关键日志记录)。
记录器可以通过实现BeginScope
method来访问信息,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;
}
}
}
对象,并简单地迭代对象直到找到属性:
does pretty much the same
Serilog in the log event但存储所有属性RequestId
。这就是为什么你没有找到qazxswpoi的明确引用,但是当你指定日志字符串格式来包含它时它仍然存在。