c# - Serilog SourceContext 类名仅通过 appsettings.json 唯一方法

标签 c# asp.net .net asp.net-core serilog

我在 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}"
        }
      }
    }
  ]
}

请注意,您需要包含 NuGetSerilog.ExpressionsSerilog.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/

相关文章:

c# - 单元测试HQL查询

c# - HttpClient in using 语句导致任务取消

asp.net - 在 .net 中,是否有与 Server.HTMLEncode() 相反的函数?

c# - 带分页的自定义数据表

c# - 有没有更好的方法来避免使用 winforms 的无限循环?

c# - Win32_MountPoint 和 Win32_Volume 在 Windows XP 上的可用性?

c# - 反序列化器不知道映射到该契约的任何类型

c# - 了解用户是否喜欢某个 Facebook 页面。使用 Facebook C# SDK

asp.net - 将 MSIL 自动转换为 JavaScript 有用吗?

c# - 我们可以在 Windows 应用程序中使用 Jquery 吗?