我可以在输出模板中只写类名而不写全名吗?

问题描述 投票:0回答:2

这是我的日志配置:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information",
        "System": "Warning",
        "System.Net.Http.HttpClient": "Warning",
        "Hangfire": "Warning"
      }
    },
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "Enrich": [ "FromLogContext" ],
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {SourceContext}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "%CUROUTDIR%\\..\\Logs\\%PROCESSNAME%\\%PROCESSNAME% .txt",
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true,
          "retainedFileCountLimit": 31,
          "fileSizeLimitBytes": 5242880,
          "outPutTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"
        }
      }
    ]
  }
}

这会产生如下结果:

[16:31:44 INF] WebHostApplicationBootstrapper`1 Init end in 00:00:03.7921289 OPG.Foundation.GenericHostApplicationBootstrapper
[16:31:44 WRN] Environment: Development OPG.Foundation.GenericHostApplicationBootstrapper
[16:31:46 FTL] Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development. Microsoft.EntityFrameworkCore.Model.Validation
[16:31:49 INF] Now listening on: https://localhost:5001 Microsoft.Hosting.Lifetime
[16:31:49 INF] Now listening on: http://localhost:5000 Microsoft.Hosting.Lifetime

正如您所看到的,源上下文已很好地添加到输出模板中,但它显示了类的完整全名,包括程序集等。

对于控制台来说,这对我来说有点太混乱了 - 我可以以某种方式只显示类名而不是源上下文的全名吗?

serilog
2个回答
2
投票

我使用 Serilog.Expressions 和计算属性解决了这个问题:

.Enrich.WithComputed("SourceContextName", "Substring(SourceContext, LastIndexOf(SourceContext, '.') + 1)")

然后可以在输出模板中使用:

"[{Timestamp:HH:mm:ss} {Level:u3} {SourceContextName}]: {Message:lj}{NewLine}{Exception}"```

如果您不需要该属性用于其他目的(Seq f.ex 中的查询),您也可以直接在输出模板中包含子字符串表达式。


0
投票

我在这个场景中遇到了一个问题,其中我的一些

SourceContext
条目是通用类,并且在来自实现的类的 dll 版本字符串的输出字符串中包含句点;这段代码最终为我解决了这个问题:

Log.Logger = new LoggerConfiguration()
             .Enrich.FromLogContext()
             .Enrich.WithComputed("SourceContextWithoutDll", "Substring(SourceContext, 0, if LastIndexOf(SourceContext, '`') > 0 then LastIndexOf(SourceContext, '`') else Length(SourceContext))")
             .Enrich.WithComputed("SourceContextName", "Substring(SourceContextWithoutDll, LastIndexOf(SourceContextWithoutDll, '.') + 1)")
             .ReadFrom.Configuration(configuration)
             .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {SourceContextName} {Level:u3}] {Message:lj}{NewLine}{Exception}")
             .CreateLogger();
© www.soinside.com 2019 - 2024. All rights reserved.