serilog / serilog-settings-configuration

A Serilog configuration provider that reads from Microsoft.Extensions.Configuration
Apache License 2.0
446 stars 129 forks source link

Constructor parameters - support objects with collection properties #314

Closed sfkoch closed 4 months ago

sfkoch commented 2 years ago

I've been trying to configure Serilog.Sinks.Splunk.EventCollectorSink from appsettings.json, but can't get it to construct the CustomFields object for the "fields" parameter. When I provide an array of 3 CustomField objects, TryBuildCtorExpression is trying and failing to find a constructor for List<CustomField> that takes 3 arguments.

This is the JSON I've tried:

    "WriteTo:EventCollector": {
      "Name": "EventCollector",
      "Args": {
        "splunkHost": "redacted",
        "eventCollectorToken": "redacted",
        "restrictedToMinimumLevel": "Warning",
        "host": "%COMPUTERNAME%",
        "fields": {
          "$type": "Serilog.Sinks.Splunk.CustomFields, Serilog.Sinks.Splunk",
          "customFields": [
            {
              "$type": "Serilog.Sinks.Splunk.CustomField, Serilog.Sinks.Splunk",
              "name": "name1",
              "value": "value1"
            },
            {
              "$type": "Serilog.Sinks.Splunk.CustomField, Serilog.Sinks.Splunk",
              "name": "name2",
              "value": "value2"
            },
            {
              "$type": "Serilog.Sinks.Splunk.CustomField, Serilog.Sinks.Splunk",
              "name": "name3",
              "value": "value3"
            }
          ]
        }
      }
    }

I also tried structuring "fields" for the fallback to ConfigurationBinding.Get in ObjectArgumentValue.ConvertTo, but that failed because CustomField doesn't have a default constructor.

Perhaps TryBuildCtorExpression needs something like TryCreateContainer from ConvertTo for when parameterType is a collection?

nblumhardt commented 4 months ago

Hi @sfkoch; this change has now been published to NuGet in version 8.0.1-dev-00583 thanks to @ChristofferGersen's #405.

Are you able to check that package out and let us know whether your scenario is now fully covered? Many thanks!

sfkoch commented 4 months ago

I've confirmed that with version 8.0.1-dev-00583 I'm able to initialize CustomFields from appsettings.json where I wasn't able to in 7.0.0. Thank you!

nblumhardt commented 4 months ago

Fantastic; thank you, @sfkoch 👍