我在 Blazor(服务器)项目中使用 Serilog ASP.NET Core,我通过 appsettings.json
配置记录器,这就是我的输出模板的样子:
"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u4}] ] [{SourceContext}] {Message:lj}{NewLine}{Exception}"
我使用 builder.Host.UseSerilog()
将其添加到应用程序中,并使用 ILogger
将其注入(inject)到我的组件中。
我想要的是仅显示类名称,而不是像 {SourceContext}
那样显示完整的程序集+类名称。
可能吗?
我已经尝试过这个: serilog format SourceContext for showing only assembly name
之后记录器的配置 (appsettings.json
) 不起作用。
另一个问题有一种基于代码的方法,而我更喜欢仅通过 appsettings.json
进行配置。
最佳答案
您可以通过 ExpressionTemplate
应用表达式.
Serilogs GitHub 页面显示 recipe仅记录类型名称而不记录命名空间。
Trim down
SourceContext
to a type name only:Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)
This expression takes advantage of
LastIndexOf()
returning -1 when no . character appears in SourceContext, to yield a startIndex of 0 in that case.
您的 appsettings.json
配置必须指定使用 ExpressionTemplate
。对于如下所示的 Console
记录器。
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"formatter": {
"type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions",
"template": "{@t:HH:mm:ss} - {@l:u} - {Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)}: {@m}\n{@x}"
}
}
}
]
}
请注意,您需要包含 NuGet
包 Serilog.Expressions和 Serilog.Settings.Configuration从3.3.0版本开始。
<PackageReference Include="Serilog.Expressions" Version="3.3.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
关于c# - Serilog SourceContext 类名仅通过 appsettings.json 唯一方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72118988/