带有Asp.Net Core 2.1的Serilog不能从appsettings.json写入

时间:2019-01-10 16:59:37

标签: c# asp.net-core-webapi serilog

我正在尝试配置Serilog以从ASP.NET Core 2 WebApi中的appsettings.json文件中读取设置。

我在appsetting.json文件的根目录中有以下内容;

"Serilog": {
    "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Async", "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel":  "Information",
    "WriteTo": [
      {
        "Name": "Async",
        "Args": {
          "configure": [
            {
              "Name": "File",
              "Args": { "pathFormat": "Logs\\Serilog\\log.txt" },
              "RollingInterval": "Day"
            },
            {
              "Name": "MSSqlServer",
              "Args": {
                "connectionString": "myconnectionstring",
                "schemaName": "Schema",
                "tableName": "Logs",
                "batchPostingLimit": 1000,
                "period": 30
              }
            }
          ]
        }
      }
    ]
  }

在我的Startup.cs中,我有以下内容;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        var log = new LoggerConfiguration()
            .ReadFrom.Configuration(Configuration)
            .CreateLogger();

        loggerFactory.AddSerilog(log);

如果我运行以下命令,那么输出将非常完美,因此我知道其原因在于转至appsettings;

var log = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .WriteTo.MSSqlServer("connectionString", "Logs", schemaName:"Schema")
            .WriteTo.File("Logs\\Serilog\\log.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();

然后在我的Program.cs中;

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(config =>
                config.AddJsonFile(
                    x =>
                    {
                        x.Path = "appsettings.json";
                        x.Optional = true;
                        x.ReloadOnChange = true;
                    })
                .AddJsonFile(
                    x =>
                    {
                        x.Path = "appsettings.{currentEnv}.json";
                        x.Optional = true;
                        x.ReloadOnChange = true;
                    })
            )
            .UseStartup<Startup>()
            .Build();

请注意,appsettings.json和特定于环境的当前都包含相同的数据。

我安装了以下版本的Serilog;

Serilog 2.7.1 Serilog.spNetCore 2.1.1 Serilog.Enrichers.Environment 2.1.2 Serilog.Settings.Configuration 3.0.1 Serilog.Sinks.Async 1.3.0 Serilog.Sinks.File 4.0.0 Serilog.Sinks.MSSqlServer 5.1.2

1 个答案:

答案 0 :(得分:3)

在Program.cs文件中尝试以下操作:

UseStartup<Startup>() .UseSerilog() .Build();

这将告诉HostBuilder使用Serilog软件包。