Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 280
OmatoSoup Avatar asked Nov 16 '25 22:11

OmatoSoup


1 Answers

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.

like image 96
OmatoSoup Avatar answered Nov 18 '25 11:11

OmatoSoup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!