在AppSettings.json中为Serilog Sinks MsSqlServer配置列选项

时间:2018-02-08 17:00:52

标签: asp.net-core-2.0 appsettings serilog

我试图确定是否可以在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节点,其中包含要使用的连接字符串和表的信息。

{
  "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 Core 2项目中应该在何处以及如何配置它们?

2 个答案:

答案 0 :(得分:2)

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

现在可以使用最新的SQL Sink和 Serilog.Settings.Configuration软件包。

另外,我知道这个问题要求提供.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"
               ]
            }
         }
      }
   ]
}

答案 1 :(得分:-1)

要从Code中的appsettings访问Serilog,您可以将Serilog节点绑定到Serilog类。
以下是详细步骤 1.创建Serilog配置类

    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
  2. 代码:

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

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