在 AppSettings.json 中配置 Serilog 接收器 MsSqlServer 的列选项

Configure Column Options for Serilog Sinks MsSqlServer in AppSettings.json

我正在尝试确定是否可以在 ASP.Net Core 2 项目的 appsettings.json 文件中配置 serilog sink mssqlserver 的列选项。

我在 Program.cs 文件中创建和配置记录器。

        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .AddEnvironmentVariables()
            .Build();

        public static int Main(string[] args)
        {



            Log.Logger = new LoggerConfiguration()
                //.Enrich.WithProperty("AppName", "One Badass App") // Adds property to XML structure in properties column
                .ReadFrom.Configuration(Configuration)
                .CreateLogger();

                try
                {
                    Log.Information("Starting web host");
                    BuildWebHost(args).Run();
                    return 0;
                }
                catch (Exception ex)
                {
                    Log.Fatal(ex, "Host terminated unexpectedly");
                    return 1;
                }
                finally
                {
                    Log.CloseAndFlush();
                }
        }

我可以从 appsettings.json 文件构建配置文件,该文件包含一个 Serilog 节点,其中包含要使用的连接字符串和 table 的信息。

{
  "AppSettings": {
    "Application": {
      "Name": "Payment Processing API",
      "Version":  "1.0"
    }
  },
  "ConnectionStrings": {
    "localPaymentProcessingDb": "Server=(localdb)\mssqllocaldb;Database=PaymentProcessing;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=(localdb)\mssqllocaldb;Database=PaymentProcessing;Trusted_Connection=True;MultipleActiveResultSets=true",
          "tableName": "Logs"
        }
      }
    ]
 }

Github 上有一个未解决的问题,但我还没有找到关于它的任何其他信息。

如果无法在 appsettings.json 中配置列选项,那么在 ASP.Net 核心 2 项目中应该在哪里以及如何配置它们?

为了从代码中的应用程序设置访问 Serilog,您可以将 Serilog 节点绑定到 Serilog class。
下面是详细步骤。
1. 创建 Serilog 配置 Class

    public class SerilogConfiguration
{
    public LogEventLevel MinimumLevel { get; set; }
    public List<WriteTo> WriteTo { get; set; }
}
public class WriteTo
{
    public string Name { get; set; }
    public Args Args { get; set; }
}
public class Args
{
    public string ConnectionString { get; set; }
    public string TableName { get; set; }
    public List<StandardColumn> Add { get; set; }
    public List<StandardColumn> Remove { get; set; }
}
  1. 配置appsettings.json

代码:

{
    "Serilog": {
    "MinimumLevel": "Error",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "<our connection string>",
          "tableName": "Log",
          "Remove": [ "Properties" ],
          "Add": [ "LogEvent" ]
        }
      }
    ]
  }
}
  1. 绑定 appsetting.json 到 class

    public void ConfigureServices(IServiceCollection services)
    {           
        services.Configure<SerilogConfiguration>(Configuration.GetSection("Serilog"));            
    }
    
  2. 访问配置

    public class HomeController : Controller    {
    private readonly SerilogConfiguration _configuration;
    public HomeController(IOptions<SerilogConfiguration> configuration)
    {
        _configuration = configuration.Value;
    }       
    
    public IActionResult AppSettings()
    {
        var columnOptions = new ColumnOptions();
        var MSSqlServer = _configuration.WriteTo.Where(wt => wt.Name == "MSSqlServer").FirstOrDefault();
        // Don't include the Properties XML column.
        foreach(var columnRemove in MSSqlServer.Args.Remove)
        {
            columnOptions.Store.Remove(columnRemove);
        }
        // Do include the log event data as JSON.
        foreach (var columnAdd in MSSqlServer.Args.Add)
        {
            columnOptions.Store.Add(columnAdd);
        }
    
        Log.Logger = new LoggerConfiguration()
            .WriteTo.MSSqlServer(MSSqlServer.Args.ConnectionString, MSSqlServer.Args.TableName, columnOptions: columnOptions,
                restrictedToMinimumLevel: _configuration.MinimumLevel)
            .CreateLogger();
        return Ok("OK");
    }    }
    

如果其他人偶然发现了同样的问题,问题中的链接 GitHub 问题现在包含答案:

This is now possible with the latest SQL sink and Serilog.Settings.Configuration packages.

此外,我知道这个问题需要 .NET Core 2 的答案,听起来链接的 GitHub 页面回答了 2,我使用的是 .NET Core 3.1,以下对我有用(希望它也适用于 2)

我安装了 Serilog.Settings.Configuration Nuget 包并使用了以下 Serilog appsettings.json 配置:

"Serilog":{
   "MinimumLevel":"Information",
   "WriteTo":[
      {
         "Name":"MSSqlServer",
         "Args":{
            "connectionString":"DbContext",
            "tableName":"EventLog",
            "autoCreateSqlTable":true,
            "columnOptionsSection":{
               "addStandardColumns":[
                  "LogEvent"
               ],
               "removeStandardColumns":[
                  "MessageTemplate",
                  "Properties"
               ]
            }
         }
      }
   ]
}