jsonemailasp.net-core.net-coreserilog

.net Core and Serilog Email sink - json config


I'm using .net Core 2.0 and Serilog Email sink. I have problem to configure email sink with appsettings.json. The same configuration from program.cs is working while one from appsetting.json isn't.

Here is code from appsettings.json

Here is code from program.cs


Solution

  • The settings system (ReadFrom.Configuration()) really only does try to call methods and extension methods that it can discover and pass arguments provided from the configuration file.

    Unfortunately, it only supports basic types for the time being (convertible to/from string and a few more specific cases) and therefore, parameters of type EmailConnectionInfo cannot be provided.

    As a workaround, though, if you only need to pass in a few parameters, you can create your own extension method that accepts the parameters that you need and call it from the configuration system.

    In your case, you would need to do the following :

    First, define an extension method EmailCustom(...) that can be plugged on WriteTo (which is of type Serilog.Configuration.LoggerSinkConfiguration) and returns a LoggerConfiguration.

    This would look something like (not tested, no usings etc :P) :

    namespace Serilog{
        public static class MyCustomExtensions
        {
            public static LoggerConfiguration EmailCustom(this LoggerSinkConfiguration sinkConfiguration, string param1, int param2, LogEventLevel restrictedToMinimumLevel){
                // the actual call to configure the Email sink, passing in complex parameters
                return sinkConfiguration.Email(... ... , restrictedToMinimumLevel , EmailConnectionInfo(){
                Foo = "bar",
                Baz = param1,
                Qux = param2,
                }
                );
            }
        }
    }
    

    From that point on, you should be able to write C# code like :

    new LoggerConfiguration()
        .WriteTo.EmailCustom(param1: "my param1", param2: 42)
       // ...
        .CreateLogger();
    

    Once you have that working, you can actually define that method call in json thanks to Serilog.Settings.Configuration in that case, that would look like

    {
    "Serilog": {
        "Using" : ["TheNameOfTheAssemblyThatContainsEmailCustom"],
        "MinimumLevel": "Debug",
        "WriteTo": [
          {
            "Name": "EmailCustom",
            "Args": {
              "param1": "my param1",
              "param2": 42,
              "restrictedToMinimumLevel": "Verbose"
            }
          }]
        }
    }
    

    This strategy can be applied for other sinks and other configuration parts of Serilog as well.


    You can find a bit more about the configuration system here :