1

I am using Serilog's MSSqlServer Sink and all settings are described in the appsettings.json. I read it in as follows:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
    return WebHost.CreateDefaultBuilder(args)
        .UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); })
        .UseStartup<Startup>();
}

I would then like to amend some of the entries read from the appsettings.json file in code. I am having trouble figuring out how to get to the configuration I just read from the file. And then how do I change MSSqlServer sink specific entries?

Specifically, let's say I want to change disableTriggers in the columnOptionsSection to false from the file below. How would I do that?

For reference, here is abbreviated portion of appsettings.json with relevant parts:

"Serilog": {
  "WriteTo": [
    {
      "Name": "MSSqlServer",
      "Args": {
        "connectionString": "User ID=zzz;Password=yyy;...",
        "tableName": "LogMe",
        "autoCreateSqlTable": false,
        "batchPostingLimit": 1000,
        "period": "0.00:00:05",
        "columnOptionsSection": {
          "disableTriggers": true,
          "clusteredColumnstoreIndex": false,
          ...
        }
      }
    }
  ]
}
AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • You should see https://stackoverflow.com/a/56732924/3445247 – Mustafa Gursel Jun 25 '19 at 17:08
  • [Here](https://github.com/serilog/serilog-aspnetcore/blob/dev/samples/EarlyInitializationSample/Program.cs) seems to be a simple sample. You can use it and than manually update `IConfiguration` object – Pavel Anikhouski Jun 25 '19 at 17:11
  • @PavelAnikhouski This requires me to enter all the information in the constructor that's already defined in appsettings.json. I want to be able to access it after the fact and change some of it. The example just writes stuff. – AngryHacker Jun 25 '19 at 17:41

1 Answers1

3

First, the syntax used to target the specific configuration value is as follows.

configuration["Serilog:WriteTo:0:Args:columnOptionsSection:disableTriggers"]

Now lets change the value in the configuration. I don't think you can do it on the configuration instance directly, but you can provide it a new layer of configuration that overrides the values from the JSON file.

var overrides = new Dictionary<string, string>
{
  { "Serilog:WriteTo:0:Args:columnOptionsSection:disableTriggers", "False" },
};

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

If you would print configuration["Serilog:WriteTo:0:Args:columnOptionsSection:disableTriggers"] you would get False from the overrides instead of True from the JSON file.

Would that work for you?

FantasticFiasco
  • 1,133
  • 1
  • 8
  • 11