1

We know that we can get values from json with the IConfiguration class with the GetSection method or simply with configuration["Serilog:Properties:ApplicationName"]; in case of array with configuration.GetSection("Serilog.Enrich").Get<string[]>()

But I don't know how to retrieve the value of "serverUrl" key that is nested in the first node of the WriteTo array

"Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning",
        "Serilog": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "Properties": {
      "ApplicationName": "MyApp"
    },
    "WriteTo": [
      {
        "Name": "Seq",
        "Args": {
          "serverUrl": "http://localhost:5341"
        }
      }
    ]
  }

Any suggestion?

2
  • 1
    If you're using Serilog, why not use the package they've built to simplify reading settings? And then if you have a question about how it's reading from appsettings.json, you could always refer to the library code? If you're trying to read elements from some custom array in your appsettings.json that doesn't have convenient methods like Serilog, you could just bind the configuration to a strongly typed object that matches the structure. Commented May 12, 2022 at 13:11
  • I definitively use .ReadFrom.Configuration(configuration) in my program.cs. I have to extrapolate that value for other reason and I'm asking for general purpose when the json node is "complex". But thanks for pointing me that link that answers another doubt (how to parametrize appsetting.xxx.json ) Commented May 13, 2022 at 10:08

1 Answer 1

2

try this

var serverUrl = configuration.GetSection("Serilog").GetSection("WriteTo")
.Get<Dictionary<string,Dictionary<string,string>>[]>()[0]["Args"]["serverUrl"]; 

or using c# classes

var serverUrl = configuration.GetSection("Serilog").GetSection("WriteTo")
.Get<WriteTo[]>()[0].Args.serverUrl; 

classes

public partial class WriteTo
{
    public string Name { get; set; }

    public Args Args { get; set; }
}

public partial class Args
{
    public Uri serverUrl { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.