.net Core和Serilog Email sink - json config

时间:2018-05-17 09:04:44

标签: json email asp.net-core .net-core serilog

我正在使用.net Core 2.0和Serilog Email sink。我在使用program.cs配置电子邮件接收器时遇到问题。 appsetting.json中的相同配置正在运行,而来自sort的配置不起作用。

Here is code from appsettings.json

Here is code from program.cs

2 个答案:

答案 0 :(得分:4)

设置系统(ReadFrom.Configuration())确实只尝试调用方法和扩展方法,它可以发现并传递从配置文件提供的参数

不幸的是,它暂时仅支持基本类型(可转换为/ string以及一些更具体的情况)因此,EmailConnectionInfo类型的参数不能提供。

但是,作为一种解决方法,如果您只需要传递一些参数,则可以创建自己的扩展方法,该方法接受您需要的参数并从配置系统中调用它。

在您的情况下,您需要执行以下操作:

首先,定义EmailCustom(...) WriteTo,可插入Serilog.Configuration.LoggerSinkConfiguration(类型为LoggerConfiguration)并返回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, } ); } } }

这看起来像(未测试,没有使用等等:P):

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

从那时起,您应该能够编写C#代码,如:

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

一旦你有了这个工作,你可以在 json 中实际定义该方法调用,这要归功于 Serilog.Settings.Configuration 在这种情况下,这看起来像

onclick ="yourFunction()"

此策略也适用于Serilog的其他接收器和其他配置部件。

您可以在此处找到有关配置系统的更多信息:

答案 1 :(得分:4)

对于其他像我这样在行与行之间难以拼凑的人来说,这是使用tsimbalar提出的框架的完整答案,该框架可用于使用SendGrid发送电子邮件的解决方案。

我将以下类添加到项目的根目录(“ MyApp”)。这将从ReadFrom.Configuration(configuration).CreateLogger();中自动调用。由于appsettings中的WriteTo EmailCustom。

using System;
using System.Net;
using Serilog;
using Serilog.Configuration;
using Serilog.Events;
using Serilog.Sinks.Email;

namespace TrackumApi
{
    public static class SerilogEmailExtension
    {
        public static LoggerConfiguration EmailCustom(this LoggerSinkConfiguration sinkConfiguration,
            string fromEmail,
            string toEmail,
            string enableSsl,
            string mailSubject,
            string isBodyHtml,
            string mailServer,
            string networkCredentialuserName,
            string networkCredentialpassword,
            string smtpPort,
            string outputTemplate,
            string batchPostingLimit,
            string periodMinutes,
            string restrictedToMinimumLevel)
        {
            return sinkConfiguration.Email(new EmailConnectionInfo
            {
                FromEmail = fromEmail,
                ToEmail = toEmail,
                EnableSsl = GetBoolean(enableSsl),
                EmailSubject = mailSubject,
                IsBodyHtml = GetBoolean(isBodyHtml),
                MailServer = mailServer,
                NetworkCredentials = new NetworkCredential(networkCredentialuserName, networkCredentialpassword),
                Port = GetInt(smtpPort)
            }, outputTemplate, GetLevel(restrictedToMinimumLevel), 
                GetInt(batchPostingLimit), TimeSpan.FromMinutes(GetInt(periodMinutes))
            );
        }

      //The system hated converting the string inputs inline so I added the conversion methods:

        private static int GetInt(string instring)
        {
            return int.TryParse(instring, out var result) ? result : 0;
        }

        private static bool GetBoolean(string instring)
        {
            return bool.TryParse(instring, out var result) && result;
        }

        private static LogEventLevel GetLevel(string restrictedtominimumlevel)
        {
            return Enum.TryParse(restrictedtominimumlevel, true,
                out LogEventLevel level) ? level : LogEventLevel.Warning;
        }
    }
}

在我的原始帖子中,我修改了Program.cs,但事实证明这不是必需的。但是,在其他任何代码之前添加Serilog.Debugging.SelfLog仍然是无价的:

        Serilog.Debugging.SelfLog.Enable(Console.Out);
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", true, true)
            .Build();

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

最后,我对appsettings.json进行了如下修改(请原谅,但我认为这可能对某些人也有帮助):

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

  "Serilog": {
    "Using": [ "Serilog", "Serilog.Sinks.Console", "Serilog.Sinks.File", "MyApp" ],
    "MinimumLevel": {
      "Default": "Verbose",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning",
        "Microsoft.AspNetCore.Authentication": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss.fff} [{Level}] {SourceContext} {Message}{NewLine}{Exception}",
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\\Temp\\Logs\\MyApp.log",
          "fileSizeLimitBytes": 1000000,
          "rollOnFileSizeLimit": "true",
          "shared": "true",
          "flushToDiskInterval": 3,
          "outputTemplate": "[{Timestamp:MM/dd/yy HH:mm:ss} [{Level}] {SourceContext} {Message}{NewLine}{Exception}",
          "restrictedToMinimumLevel": "Verbose"
        }
      },
      {
        "Name": "EmailCustom",
        "Args": {
          "fromEmail": "no-reply@mydomain.com",
          "toEmail": "me@mydomain.com",
          "enableSsl": false,
          "mailSubject": "MyApp Message",
          "isBodyHtml": true,
          "mailServer": "smtp.sendgrid.net",
          "networkCredentialuserName": "mysendgridusername",
          "networkCredentialpassword": "mysendgridpassword",
          "smtpPort": 587,
          "outputTemplate": "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}",
          "batchPostingLimit": 10,
          "periodMinutes": 5,
          "restrictedToMinimumLevel": "Verbose"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "MyApp"
    }
  }

}

HTH!