.net Core and Serilog Email sink - json config

◇◆丶佛笑我妖孽 提交于 2020-01-04 03:19:11

问题


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.


回答1:


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 :

  • the project's README Serilog.Settings.Configuration
  • examples of what can be done through configuration (shameless plug :p)


来源:https://stackoverflow.com/questions/50387469/net-core-and-serilog-email-sink-json-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!