首页 文章

ASP.NET Core记录了2个不同的文件

提问于
浏览
1

将默认的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个文件中?

2 回答

  • 0

    Serilog支持,但您似乎缺少相关代码 . 在 Startup 方法中,您应该设置SeriLog配置 . 在那里,您可以配置它使用接收器和过滤器将不同的数据记录到不同的文件中 .

  • 1

    如果要使用单个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中的日志级别和描述:

    enter image description here

相关问题