ASP.NET Core登录2个不同的文件 [英] ASP.NET Core logging in 2 different files

查看:100
本文介绍了ASP.NET Core登录2个不同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将默认的ASP.NET核心日志记录与Serilog结合使用时,是否可以将错误写入errors.log,将信息写入informations.log

When using the default ASP.NET core logging in combination with Serilog, is it possible to write errors to errors.log and information to informations.log

using Microsoft.Extensions.Logging;
using Serilog;

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

Appsettings.json:

Appsettings.json:

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

我想要一个日志文件,在其中我可以看到已完成的请求以及诸如此类的信息,仅是信息日志.还有一个带有错误的日志,用于调试目的.如何将不同的东西记录到2个文件中?

I want one logging file where I can see the requests which are done and stuff like that, just the info log. And one log with errors for debugging purposes. How can I log different things to 2 files?

推荐答案

如果要使用单个Logger对象,则可以按级别过滤日志类型:

If you want to use a single Logger object you can filter log type by level:

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"

文档中的日志级别和说明:

The log levels and descriptions from the docs:

这篇关于ASP.NET Core登录2个不同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆