我被要求在开发中编写日志级别“信息”、“警告”和“错误”,但它们都在一个单独的文件中,这样我就有仅包含信息日志的 information.txt、仅包含警告日志的 warning.txt、Error.txt仅包含错误日志。
这是我目前的实现(它有效)。
在 Program.cs 中:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseSerilog((webHostBuilderContext, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(webHostBuilderContext.Configuration);
});
});
在应用程序设置中:
"Serilog": {
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "wwwroot/Logs/log.txt",
"rollingInterval": "Day",
"reatinedFileCountLimit": 14,
"restrictedToMinimumLevel": "Information"
}
}
]
},
我已经安装了 Serilog.Expressions 包并阅读了文档,我知道我必须使用这样的东西
"Filters": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@l = 'Information'"
}
}
]
但我不明白它应该放在哪里。我尝试将它放在 Args 中或 Args 和 Name 之间,但它不起作用,有人可以帮助我吗?
我已经在 stackoverflow 上阅读了很多线程,但没有任何效果:(
这有效,但不能使用文档。
using Serilog;
using Serilog.Events;
Log.Logger = new LoggerConfiguration()
.WriteTo.Logger(l => l
.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information)
.WriteTo.File(
path: "information.txt"))
.WriteTo.Logger(l => l
.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
.WriteTo.File(
path: "error.txt"))
.CreateLogger();
Log.Information("test Information");
Log.Error("test Error");