Serilog 不从 json 获取控制台配置

Serilog does not take console config from json

我的 asp.net 核心 (5) 应用程序中有以下内容:

var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(config)
    .CreateLogger();

并且在appsettings.json以下

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "MyApp": "Information",
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithProcessId",
      "WithThreadId"
    ],
    "WriteTo": [
      {
        "Name": "Console",
        "outputTemplate": "{Timestamp:G}[{Level:u3}] ** {Message} ** ({SourceContext}) {NewLine:1}{Exception:1}"
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\logs\MyApp\log.txt",
          "outputTemplate": "{Timestamp:G}[{Level:u3}] ** {Message} *** ({SourceContext}) {NewLine:1}{Exception:1}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\logs\MyApp\log.json",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      },
      {
        "Name": "Seq",
        "Args": {
          "_serverUrl": "http://localhost:5341",
          "serverUrl": "http://localhost:8081"
        }
      }
    ]
  },

  "AllowedHosts": "*"
}

当我在 txt 文件中有 **(我将其用于测试目的)时,console 输出似乎是 default 一个 - config 文件中的任何更改似乎都不会影响它...

我的项目中安装了以下软件包:

<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="5.0.0" />

<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />

根据 serilog console sink documentation 你需要在 Args 属性

中指定格式
{
  "Serilog": {
    "WriteTo": [
      {
          "Name": "Console",
          "Args": {
            "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
            "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}"
          }
      }
    ]
  }
}