Search code examples
c#logging.net-coreserilog

How to overwrite application name specified in appsettings.json when using Serilog?


My appsettings.json looks like this:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {

              "Name": "File",
              "Args": {

                "path": "%APPDATA%\\FancyProject\\logs\\RR.log",
                "formatter": "Serilog.Formatting.Json.JsonFormatter",
                "rollingInterval": "Day",
                "retainedFileCountLimit": 20,
                "buffered": false
              }
            }
          ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", "WithExceptionDetails" ],
    "Properties": {
      "Application": "SampleName"
    }
  }
}

Loading the settings:

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

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

I'd like to use the same config file for multiple projects in my solution but with a different application name in order to distinguish between services.

Is there a way to change the application name ("SampleName" in my config) in code when loading the config?


Solution

  • I solved it by removing the Properties section from the config and load it this way:

    Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .Enrich.WithProperty("ApplicationName", "my application")
                .CreateLogger();
    

    PavelAnikhouski's (deleted) answer was actually the correct answer to my question but I think directly adding the correct application name is cleaner than modifying a placeholder.