我想要一个用于信息和警告的日志,以及另一个用于错误和致命的日志。
我想使用json文件而不是Fluent API,并且只使用json,因为我读到从json获取部分配置和从Fluent API获取另一部分配置存在问题。
但是我有一个问题,在这两个文件中都写入了所有日志,不仅一个文件中包含信息和警告,另一个文件中还包含错误和致命日志。
我有看到这个问题,但它不使用json文件。
我的program.cs文件是这样的:
builder.Services
.AddSerilog()
.AddHostedService<Worker>()
.InstalarServicios(builder.Configuration);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();
这是我的 json 文件:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"LogEventLevel": "Information, Warning",
"path": "./logs/log-informacion-.txt",
"rollingInterval": "Day"
}
},
{
"Name": "File",
"Args": {
"LogEventLevel": "Error, Fatal",
"path": "./logs/log-errores-.txt",
"rollingInterval": "Day"
}
}
]
}
}
在json文件中,我尝试对一个文件使用 "RestrictedToMinimumLevel": "Information" ,对第二个文件使用 "RestrictedToMinimumLevel": "Error" ,但结果始终相同,它创建两个文件并在两个文件中写入相同的日志,无论它是信息还是错误。
我如何才能只在一个文件中写入信息和警告,而在其他错误和致命日志中写入?
谢谢。
要将日志分成两个不同的文件,即信息和警告,我们可以使用两种方法:
子记录:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Logger(c => c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
.WriteTo.File("Debug.log"))
.WriteTo.Logger(c => c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
.WriteTo.File("Error.log"))
.CreateLogger();
Serilog.Sinks.Map包:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Map(evt => evt.Level, (level, wt) => wt.File($"{level}.log"))
.CreateLogger();
根据您的要求编辑上述代码;您将能够非常轻松地实现它。
您似乎正在尝试过滤日志,然后将这些过滤后的日志写入不同的文件,正如我在链接示例中看到的那样。
您可以在 json 文件中尝试此配置设置:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@Level = 'Information' or @Level = 'Warning'"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "./logs/log-informacion-.txt",
"rollingInterval": "Day"
}
}
]
}
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@Level = 'Error' or @Level = 'Fatal'"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "./logs/log-errores-.txt",
"rollingInterval": "Day"
}
}
]
}
}
}
]
}
}
在此配置中,可以看到不同的过滤和写入每个记录器内的不同文件。