簡體   English   中英

ASP.NET Core登錄2個不同的文件

[英]ASP.NET Core logging in 2 different files

當將默認的ASP.NET核心日志記錄與Serilog結合使用時,是否可以將錯誤寫入errors.log,將信息寫入informations.log

using Microsoft.Extensions.Logging;
using Serilog;

loggerFactory.AddSerilog();
loggerFactory.AddFile(Configuration.GetSection("Logging"));

Appsettings.json:

"Logging": {
    "PathFormat": "path-{Date}.log",
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information",
      "System": "Information",
      "Microsoft": "Information"
    }
  }

我想要一個日志文件,在其中可以看到已完成的請求以及諸如此類的信息,僅是信息日志。 還有一個帶有錯誤的日志,用於調試目的。 如何將不同的東西記錄到2個文件中?

如果要使用單個Logger對象,則可以按級別過濾日志類型:

using Serilog;
using Serilog.Events;

Log.Logger = new LoggerConfiguration()
            // Restricts logs to: Debug, Information, Warning, Error and Fatal
            .MinimumLevel.Debug()
            // Logs Information, Warning, Error and Fatal to "info-logs.txt" file
            .WriteTo.File(path: "info-logs.txt", restrictedToMinimumLevel: LogEventLevel.Information)
            // Logs Error and Fatal to "error-logs.txt" file
            .WriteTo.File(path: "error-logs.txt", restrictedToMinimumLevel: LogEventLevel.Error) 
            .CreateLogger();

Log.Verbose("Loggin Verbose..."); // Won't log, because the Logger "MinimumLevel" is set to Debug
Log.Debug("Loggin Debug..."); // Won't log, because there is no sink that takes Debug
Log.Information("Loggin Information..."); // Logs into "info-logs.txt"
Log.Warning("Loggin Warning..."); // Logs into "info-logs.txt"
Log.Error("Loggin Error..."); // Logs into "info-logs.txt" and "error-logs.txt"
Log.Fatal("Loggin fatal..."); // Logs into "info-logs.txt" and "error-logs.txt"

來自docs的日志級別和說明:

在此處輸入圖片說明

Serilog支持這一點,但是您似乎缺少相關的代碼。 Startup方法中,您應該設置SeriLog配置。 您可以在那里配置它,以便使用接收器和過濾器將不同的數據記錄到不同的文件中。

暫無
暫無

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

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