Serilog MSSQLServer +电子邮件(带有自定义主题)接收器

时间:2019-04-06 17:27:22

标签: asp.net-core serilog

所需状态:

以下代码可以工作...但是理想情况下,我想在“ Serilog”下的“ AppSettings”部分中配置所有这些功能,但是即使使用默认的电子邮件主题行,我也无法使其正常工作(要求#3)。

目标/要求:

  1. 将信息级别和更高级别的日志记录到SQL数据库。
  2. 此外,如果日志级别为“致命/严重”,我还需要登录 它发送到电子邮件。
  3. 电子邮件主题行还应包括 发送电子邮件的环境(即DEV / Staging / Production)

说明:

我为以下两次不同的尝试创建了两个单独的ASP NET Core 2.2应用程序。

当前有效的实施方案:

〜/ AppSettings。{Environment} .json

...
  "SqlLogger": {
    "ConnectionString": <connStr>,
    "SchemaName" : "Log"
    "TableName": <tableName>
  },
 "EmailLogger": {
    "FromEmail": <email>,
    "ToEmail": <email>,
    "MailServer": <server>,
    "Subject": "Fatal Error in the App"
  },
...

〜/ Models / EmailLoggerSettings.cs

public class EmailLoggerSettings
{
    public string FromEmail { get; set; }
    public string ToEmail { get; set; }
    public string MailServer { get; set; }
    public string Subject { get; set; }
}

〜/ Models / SqlLoggerSettings.cs

public class SqlLoggerSettings
{
    public string ConnectionString { get; set; }
    public string SchemaName { get; set; }
    public string TableName { get; set; }
}

〜/ Program.cs

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((builderContext, config) =>
        {
            var environment = builderContext.HostingEnvironment;
            config
                .SetBasePath(environment.ContentRootPath)
                .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile(path: $"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();
            }
        )
        .UseIIS()
        .UseIISIntegration()
        .UseStartup<Startup>();

〜/ Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration.GetSection("ApplicationSettings"));
    services.Configure<EmailLoggerSettings>(Configuration.GetSection("EmailLogger"));
    services.Configure<SqlLoggerSettings>(Configuration.GetSection("SqlLogger"));
    ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<EmailLoggerSettings> emailLoggerSettings, IOptions<SqlLoggerSettings> sqlLoggerSettings)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Verbose()
                .WriteTo.MSSqlServer(
                        connectionString: sqlLoggerSettings.Value.ConnectionString, 
                        schemaName: "dbo",
                        tableName: sqlLoggerSettings.Value.TableName, 
                        columnOptions: new ColumnOptions(), 
                        restrictedToMinimumLevel: LogEventLevel.Information
                    )
            .MinimumLevel.Verbose()
                .WriteTo.Email(
                        fromEmail: emailLoggerSettings.Value.FromEmail,
                        toEmail: emailLoggerSettings.Value.ToEmail,
                        mailServer: emailLoggerSettings.Value.MailServer,
                        mailSubject: $"[{System.Environment.MachineName}] {emailLoggerSettings.Value.Subject}",
                        restrictedToMinimumLevel: LogEventLevel.Fatal
                    )
            .CreateLogger();



        loggerFactory.AddSerilog();


        //Serilog.Debugging.SelfLog.Enable(msg =>
        //{
        //    Debug.Print(msg);
        //    Debugger.Break();
        //});

        Serilog.Log.Information("Host starting ...");
        ...
    }

基于应用设置的配置(不起作用)

〜/ AppSettings。{Environment} .json

  "Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "<connStr>",
          "schemaName" : "Log"
          "tableName": <tableName>

        }
      },
      {
        "Name": "Email",
        "Args": {
          "restrictedToMinimumLevel": "Fatal"
        }
      }
    ]
  },

〜/ Program.cs

public class Program
{
    public static IConfiguration Configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile(path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true, reloadOnChange: true)
                    .Build();
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(Configuration)
            .CreateLogger();

         CreateWebHostBuilder(args).Build().Run();
...

〜/ Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
     loggerFactory.AddSerilog();

     //Serilog.Debugging.SelfLog.Enable(msg =>
     //{
     //    Debug.Print(msg);
     //    Debugger.Break();
     //});
...

0 个答案:

没有答案