Мар*_*вић 3 email json serilog .net-core asp.net-core
我正在使用.net Core 2.0和Serilog电子邮件接收器。我在配置电子邮件接收器时遇到问题appsettings.json。from的相同配置program.cs有效,而from 的相同appsetting.json无效。


对于像我这样无法在字里行间拼凑出问题的人来说,这里是一个完整的答案,使用 tsimbalar 提供的框架来解决使用 SendGrid 发送电子邮件的解决方案。
我将以下类添加到我的项目的根目录(“MyApp”)。这会从 ReadFrom.Configuration(configuration).CreateLogger() 自动调用;由于应用程序设置中的 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我原来的帖子中,我修改了 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();
Run Code Online (Sandbox Code Playgroud)
最后我修改了 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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
哈!
设置系统(ReadFrom.Configuration())实际上仅尝试调用它可以发现并传递从配置文件提供的参数的方法和扩展方法。
不幸的是,它暂时仅支持基本类型(可与其他类型进行相互转换string),因此EmailConnectionInfo无法提供类型参数。
但是,作为一种解决方法,如果只需要传递一些参数,则可以创建自己的扩展方法,该方法接受所需的参数并从配置系统中调用它。
对于您的情况,您需要执行以下操作:
首先,定义一个可以插入的扩展方法 (类型为)并返回。EmailCustom(...)WriteToSerilog.Configuration.LoggerSinkConfigurationLoggerConfiguration
这看起来像(未经测试,没有使用等: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,
}
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
从那时起,您应该能够编写如下的C#代码:
new LoggerConfiguration()
.WriteTo.EmailCustom(param1: "my param1", param2: 42)
// ...
.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
一旦完成工作, 在这种情况下,实际上您可以在json中定义该方法调用,这要归功于Serilog.Settings.Configuration。
{
"Serilog": {
"Using" : ["TheNameOfTheAssemblyThatContainsEmailCustom"],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "EmailCustom",
"Args": {
"param1": "my param1",
"param2": 42,
"restrictedToMinimumLevel": "Verbose"
}
}]
}
}
Run Code Online (Sandbox Code Playgroud)
此策略也可以应用于Serilog的其他接收器和其他配置部分。
您可以在这里找到有关配置系统的更多信息:
| 归档时间: |
|
| 查看次数: |
1773 次 |
| 最近记录: |