簡體   English   中英

使用 Net Core 2.2 覆蓋 appsettings.production 中的 Serilog 設置

[英]Serilog override settings in appsettings.production with Net Core 2.2

當我想根據不同的環境寫入數據庫時,我遇到了 serilog 的問題。 Serilog 覆蓋我的 appsettings.production.json 並始終采用 appsettings.json 中的設置,即使在生產模式下也是如此!

我在本地appsettings.json中的代碼

"Serilog": {
        "Using": [ "Serilog.Sinks.MSSqlServer" ],
        "MinimumLevel": {
            "Default": "Debug",
            "Override": {
                "Microsoft": "Warning",
                "System": "Warning"
            }
        },
        "WriteTo": {
          "Console" : {"Name": "Console"},
          "Sql": {
             "Name": "MSSqlServer",
             "Args": {
                "connectionString": "Server=MyServerInDev\\SQLSERVER;Database=MyDBDev;user id=ui;password=pw_;ConnectRetryCount=0;MultipleActiveResultSets=true",
                "tableName": "Log",
                "autoCreateSqlTable": true
            }
        }
    }, 

appsettings.production.json

"Serilog": {
        "Using": [ "Serilog.Sinks.MSSqlServer" ],
        "MinimumLevel": {
            "Default": "Warning",
            "Override": {
                "Microsoft": "Warning",
                "System": "Warning"
            }
        },
        "WriteTo": {
          "Console" : {"Name": "Console"},
          "Sql": {
             "Name": "MSSqlServer",
             "Args": {
                "connectionString": "Server=MyServerInProd\\SQLSERVER;Database=MyDBProdv;user id=ui;password=pw_;ConnectRetryCount=0;MultipleActiveResultSets=true",
                "tableName": "Log",
                "autoCreateSqlTable": true
            }
        }
    },

我的程序.cs

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

            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

我錯過了什么? 以及為什么 serilog 采用 appsettings.json 設置而不是 appsettings.production.json 即使在 prod 模式下

請注意,appsettings.production.json 中的其他設置工作正常。 只有 serilog 中的設置會導致問題

找到了。 原因是 Serilog 將接收器配置添加到數組中,並且 appsettings 的兩個文件中的每一個都只是添加了另一個接收器而不是替換它們。 解決方案是明確指出每個接收器的數組索引。 答案的學分: nblumhardt 經測試,有效。

"WriteTo": {
  "0": {
    "Name": "File",
    "Args": {
      "path": "./logs/myapp-.txt",
      "rollingInterval": "Day"
    }
  }
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM