How to use prefix syntax to retrieve a deeply nested setting [array] from an appsettings.json file

207 views Asked by At

Is there a way to retrieve a specific WriteTo object from the following Serilog json snippet from my appsettings.json file using the prefix syntax?

here is the file section

"Serilog": {
"Using": [ "Serilog.Enrichers.Thread", "Serilog.Enrichers.Process", "Serilog.Enrichers.MachineName", "Serilog.Enrichers.FromLogContext" ],
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"MinimumLevel": {
  "Default": "Information",
  "Override": {
    "Microsoft": "Warning",
    "System": "Warning"
  }
},
"WriteTo": [
  {
    "Name": "Console",
    "Args": {
      "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
    }
  },
  {
    "Name": "ApplicationInsights",
    "Args": {
      "instrumentationKey": "your-instrumentation-key",
      "restrictedToMinimumLevel": "Information"
    }
  },            
  {
    "Name": "Seq",
    "Args": {
      "serverUrl": "https://localhost:5341/",
      "apiKey": ""
    }
  }
]
},

Considering the WriteTo section is an array, I tried using

var ary = _config.GetSection("Serilog:WriteTo").GetChildren();

to create an array I could then filter, but it returns an array of three objects, that are empty.

I was hoping there was a way to use the prefix, something like "Serilog:WriteTo:Name='Seq' to get that section and then I could retrieve the values from that section.

Is there a way to use some type of prefix syntax to accomplish this? Or is there a better way?

1

There are 1 answers

1
Serge On BEST ANSWER

you can try this code

var writeTo = configuration.GetSection("Serilog:WriteTo")
                                     .Get<List<WriteTo>>()
                                     .ToDictionary(x => x.Name, x => x.Args);

string outputTemplate = writeTo["Console"]["outputTemplate"];

public class WriteTo
{
    public string Name { get; set; }
    public Dictionary<string,string> Args { get; set; }
}

But IMHO it would be easier to get data,if you redo your config from list to a dictionary by removing Name, and replasing Args by Name value. In this case a custom class and conversion will not be needed.