簡體   English   中英

Serilog 多個文件 appsettings.json

[英]Serilog multiple files appsettings.json

我試圖將 serilog 配置為寫入多個文件,但沒有任何運氣。 使用此配置它只是寫入第二個文件?

{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\audit-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Information"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\error-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Error"
        }
      }
    ]
  }
}

或者有什么方法可以將許多記錄器加載到具有來自 appsettings.json 的不同配置的軟件中。 像這樣的東西?

var errorLogConfiguration = 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 = new LoggerConfiguration()
    .ReadFrom
    .Configuration(errorLogConfiguration)
    .CreateLogger();

我找到了解決方案。 為 appsettings.json、ErrorLog 和 AuditLog 創建了單獨的部分。

  "ErrorLog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\error-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Error"
        }
      }
    ]
  },
  "AuditLog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\audit-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Information"
        }
      }
    ]
  }

現在我可以創建 2 個單獨的記錄器:

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

            var errorSection = errorLogConfiguration.GetSection("ErrorLog");
            var auditSection = errorLogConfiguration.GetSection("AuditLog");

            _log = new LoggerConfiguration()
                .ReadFrom
                .ConfigurationSection(errorSection)
                .CreateLogger();

            _auditLog = new LoggerConfiguration()
                .ReadFrom
                .ConfigurationSection(auditSection)
                .CreateLogger();

哪個更適合我的需要。

由於 Serilog 和任何接收器的簡單文檔而苦苦掙扎了幾天之后,這最終對我有用,而無需創建任何單獨的記錄器:

"Serilog": {
    "Using": [ "Serilog.Sinks.Async" ],
    "MinimumLevel": "Verbose",
    "Enrich": [ "FromLogContext", "WithDemystifiedStackTraces" ],
    "WriteTo:Information": {
        "Name": "Async",
        "Args": {
            "Configure": [
                {
                    "Name": "RollingFile",
                    "Args": {
                        "RestrictedToMinimumLevel": "Information",
                        "Formatter": "FOOINC.API.Configuration.Logging.CustomRenderedCompactJsonFormatter, FOOINC.API.Configuration",
                        "PathFormat": "_logs\\info\\info-log.json"
                    }
                }
            ]
        }
    },
    "WriteTo:Error": {
        "Name": "Async",
        "Args": {
            "Configure": [
                {
                    "Name": "RollingFile",
                    "Args": {
                        "RestrictedToMinimumLevel": "Error",
                        "Formatter": "FOOINC.API.Configuration.Logging.CustomRenderedCompactJsonFormatter, FOOINC.API.Configuration",
                        "PathFormat": "_logs\\errors\\error-log.json"
                    }
                }
            ]
        }
    }
}

希望這可以幫助那里的任何人!!

由於缺乏有關 Serilog 的文檔,我的發現經過一段時間的錯誤,重試並幾乎放棄。 他們在 GitHub 上有所行動: https : //github.com/serilog/serilog-filters-expressions/issues/27 幾乎每個線程都得出相同的結論,即您必須創建一個 SUBLOGGER。 這是我的實現。 對於此實現,您需要以下插件:

  • 串行過濾器
  • 水槽
  • 串行日志異步

    "Serilog": { "Using": [ "Serilog.Sinks.File" ], "MinimumLevel": { "Default": "Information", "Override": { "Microsoft": "Warning", "System": "Warning" } }, "WriteTo:Information": { //this name here can be changed "Name": "Logger", //this name here is essential "Args": { "configureLogger": { "Filter": [ { "Name": "ByIncludingOnly", "Args": { "expression": "@Level = 'Information'" } } ], "WriteTo": [ { "Name": "Async", //i use async plugin from serilog "Args": { "configure": [ { "Name": "File", "Args": { "path": "Logs/Log_.txt", "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog", "rollingInterval": "Day", "retainedFileCountLimit": 7 } } ] } } ] } } },

通過配置文件幾乎沒有關於記錄器設置的文檔。 任何人都可以幫忙 - 只是一個使用記錄器設置的例子。 在示例中 - 所有日志都寫在一個 sample.txt 中。 記錄某個 API / api/health 的調用 - 在一個單獨的文件中,不包含在 sample.txt 中。 還有一個示例廣告 - IMyLogger-寫入單獨的 SampleMy.txt。 您可以添加多個部分,並按不同標准划分日志。 最好將本地日志級別設置為最小,它們將被全局級別覆蓋。 全局過濾器將從所有子記錄器中排除日志(我不使用它)。 PS抱歉英語不好)

"Serilog": {
    "MinimumLevel": "Information", //<- global error level. Ovveride all local error level
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "MinimumLevel": "Debug", // <- local error level. 
            //Only records with Information logging level will be written to the log file
           //but if ovveride global level to Debug, and dont override local error level -> it will still be global
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "log\\SampleHealthCheck-.txt", //write health-check log in different file
                  "rollingInterval": "Day",
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [CorrId:{CorrelationId}] [Op:{OperationId}] [U:{UserName}] {Message:lj}{NewLine}{Exception}"
                }
              }
            ],
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "RequestPath like '%/api/health'"
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "MinimumLevel": "Debug",
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "log\\SampleMy-.txt", //Write some log in different file. Control through code 
                  "rollingInterval": "Day",
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [CorrId:{CorrelationId}] [Op:{OperationId}] [U:{UserName}] {Message:lj}{NewLine}{Exception}"
                }
              }
            ],
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "SourceContext = 'MyProject.IMyLogger'"
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "MinimumLevel": "Information",
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "log\\Sample-.txt", //all logs, without health-check
                  "rollingInterval": "Day",
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [CorrId:{CorrelationId}] [Op:{OperationId}] [U:{UserName}] {Message:lj}{NewLine}{Exception}"
                }
              }
            ],
            "Filter": [
              {
                "Name": "ByExcluding",
                "Args": {
                  "expression": "RequestPath like '%/api/health'"
                }
              }
            ]
          }
        }
      }
    ],
    "Enrich": [
      "WithProcessName"
    ],
    "Properties": {
      "Application": "Sample",
      "Environment": "Test"
    }
  }

public class MyCommandHandler : IRequestHandler<MyCommand, Unit>
{
    private readonly ILogger _myLogger;
    private static int _count;

    public MyCommandHandler()
    {
        _myLogger = Log.ForContext<IMyLogger>();
    }

    public async Task<Unit> Handle(MyCommand request, CancellationToken cancellationToken)
    {
        _count++;

        Log.Debug("MyCommandHandler Count call = {count}",_count ); //write sample.txt
        Log.Information("MyCommandHandler Count call = {count}",_count ); //write in sample.txt
        Log.Error("MyCommandHandler Count call = {count}",_count); //write in sample.txt

        _myLogger.Information("Log from IMyLogger", _count); //write in sample.txt and in sampleMy.txt

        return Unit.Value;
    }
}

我對這個問題做了一些測試。 好消息是您的配置有效。 您的錯誤文件可能未創建,因為沒有記錄錯誤。

當第一條消息登錄到該文件時,Serilog 將創建日志文件。 如果您運行這個簡單的程序並(取消)注釋錯誤記錄,您可以確認這一點。

class Program
{
    static void Main(string[] args)
    {
        var errorLogConfiguration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json", optional: false, reloadOnChange: true)
            .Build();

        var log = new LoggerConfiguration()
            .ReadFrom
            .Configuration(errorLogConfiguration)
            .CreateLogger();
        log.Warning("Warning");
        log.Error("Error");
    }
}

暫無
暫無

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

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