Serilog MSSQLServer + Email (with custom subject) Sinks

爷,独闯天下 提交于 2019-12-25 03:30:39

问题


Desired state:

The following code works ... but ideally, I would like to have all this configured in the AppSettings under Serilog section, but I could not get it to work, even with the default email subject line (requirement #3).

Objective / Requirement :

  1. To log information level & higher logs to SQL database.
  2. Additionally, if the log level is Fatal/Critical I also need to log it to Email.
  3. The email subject line should also include the environment which is sending the email (i.e. DEV/Staging/Production)

Clarification:

I created two separate ASP NET Core 2.2 applications for the following 2 different attempts I made.

Current Working Implementation:

~/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 ...");
        ...
    }

App Setting based configuration (not working)

~/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();
     //});
...

来源:https://stackoverflow.com/questions/55551654/serilog-mssqlserver-email-with-custom-subject-sinks

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