.netasp.net-coreserilogasp.net-core-5.0asp.net-core-configuration

Serilog does not take console config from json


I have the following in my asp.net core (5) application:

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

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

and in the appsettings.json the following

{
  "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": "*"
}

when I have in the txt file the ** (I used this for test purpose) the console output seems to be the default one - any changes in the config file does not seem to affect it...

I have the following packages installed in my project:

<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" />

Solution

  • According to serilog console sink documentation you need to specify formatting inside Args property

    {
      "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}"
              }
          }
        ]
      }
    }