问题描述
在log4net中,您可以选择声明具有levelMin levelMax范围的其他文件.这样,您可以拥有一个用于调试的文件和一个用于错误的文件.我如何在serilog文件接收器中具有相同的行为.我有此代码,但只允许您指定MinimumLevel
In log4net you have the option to declare different fileappenders with a levelMin levelMax range.In that way you can have one file for debug and one file for error.How can I have the same behavior in serilog file sink.I have this code but you are only allowed to specify MinimumLevel
Log.Logger = new LoggerConfiguration()
.WriteTo.Async(a =>
{
a.RollingFile($"{AppDomain.CurrentDomain.BaseDirectory}\\Logs\\error.txt",
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error);
})
.WriteTo.Async(a =>
{
a.RollingFile($"{AppDomain.CurrentDomain.BaseDirectory}\\Logs\\log.txt",
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug);
})
.CreateLogger();
它创建了两个文件,但是在log.txt中我也看到了错误级别消息
It creates two files but in the log.txt I also see the error level messages
推荐答案
在Serilog中,您可以使用子记录器,并对其应用了过滤器:
In Serilog you can do use sub-loggers with a filter applied to each of them:
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();
Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");
Log.CloseAndFlush();
或者,如果您只想使用 Serilog.Sinks.Map 将 LogEventLevel
映射到文件.
Alternatively, you can use the Serilog.Sinks.Map if you just want to map a LogEventLevel
to a file.
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Map(evt => evt.Level, (level, wt) => wt.File($"{level}.log"))
.CreateLogger();
Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");
Log.CloseAndFlush();
这篇关于Serilog范围级别过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!