0

I have an ASP.NET Core MVC app using Serilog. Sinks are configured in the appsettings.json. I have a few sinks.

One of the sinks is not behaving. Typically I would overwrite the values of the appsettings using the UserSecrets. In this case, since the entry I want to overwrite is one of the items in a {Serilog:{WriteTo:[]}}, changing values for the one item and leaving the others as they are is not obvious. I can see one way is to have a separate IConfigurationProvider for each environment that replicates the entire WriteTo array, except for the one item being examined.

When I have a few environments and a few items in the array and the items can be moderately complex, this approach won't scale.

Is there an approach here that can scale with complexity?

1 Answer 1

1

I'll try to answer through an example. Let's say we have the following settings:

{
  "Serilog": {
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "File", "Args": { "path": "Logs/log.txt" } }
    ]
  }
}

And we want to override the file path. We would need to specify our user secrets like this:

{
  "Serilog": {
    "WriteTo": [
      { },
      { "Args": { "path": "CustomPath/log.txt" } }
    ]
  }
}

Note we specify an empty object for the first item. The JSON config provider only adds settings for properties it finds in the objects. If an object is empty, no settings are added; meaning it doesn't touch the first log target. We only change the one setting for the second log target.

Sign up to request clarification or add additional context in comments.

3 Comments

I like this behavior. Is there a citation for it?
At least the docs on the provider don't mention this. But for the general case, it helps if you remember that the config does not have a structure once it's loaded. So empty objects in JSON and such cannot result in anything being added. The first JSON sample adds three keys: Serilog:WriteTo:0:Name, Serilog:WriteTo:1:Name, and Serilog:WriteTo:1:Args:path. The second sample adds one key (overriding the existing one): Serilog:WriteTo:1:Args:path. Once you understand that, you can figure out how to override them with the various providers :)
The key realization is that {List: [1,2,3]} in appsettings and {List:[{},{},4]} in secrets results in {List: [1,2,4]}, not {List:[{},{},4]}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.