5

This is very similar to this question except its about appending arrays between two different JSON files.

I have an ASP.NET Core application

I have the following in appsettings.Development.Json

"Serilog": {
  "WriteTo": [
    {
      "Name": "ApplicationInsightsTraces",
      "Args": { "instrumentationKey": "XXXXXXXX" }
    }
  ]
}

And in appsettings.json:

"Serilog": {
  // . . . Rest of Serilog configs  
  "WriteTo": [
    {
      "Name": "Console",
      "Args": {
      "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
      "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {RequestId}-{SourceContext} {$Scope:lj}: {Message:lj}{NewLine}{Exception}"
    },
    "restrictedToMinimumLevel": "Information"
  },
}

Because Keys overwrite other keys in Appsettings.json I end up with the Console sink being overridden. Is there a syntax to allow it to be appended?

spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Justin Dearing
  • 14,270
  • 22
  • 88
  • 161

1 Answers1

6

The answer is to use WriteTo:1 and make it an object not an array in appsettings.Development.json like so:

"Serilog": {
  "WriteTo:1": 
  {
    "Name": "ApplicationInsightsTraces",
    "Args": { "instrumentationKey": "d95066c9-0b17-4e0a-84d4-bb2a4f111016" }
  }
}
spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Justin Dearing
  • 14,270
  • 22
  • 88
  • 161
  • Good find. It's touched upon in [JSON configuration](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/#json-configuration) documentation, but it's not intuitive especially for arrays. – Mark G May 04 '18 at 16:52
  • 1
    @MarkG The unit tests are the best way to figure out how to do weird stuff. – Justin Dearing May 09 '18 at 15:40
  • 1
    I have the opposite problem of OP... all my arrays concatenate and I want them to overwrite. I have no idea why everyone else seems to have the opposite experience, but this works for that scenario as well! Only problem is you can't remove extra elements, so you should have a canary value which indicates the app should ignore an array item (an empty string works for most cases... null values can't be used in appsettings, they're ignored). – user169771 Aug 09 '22 at 15:52