Serilog的子记录器过滤器无法正常工作

时间:2018-12-19 17:16:39

标签: c# logging serilog

这是我的简单配置:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Logger(l => l
        .Filter.ByExcluding(e => e.Level < LogEventLevel.Warning)
        .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Warning))
        .WriteTo.File(
            Path.Combine(HttpContext.Current.Server.MapPath("~/logs/warnings"), "log.txt"),
            rollingInterval: RollingInterval.Day,
            flushToDiskInterval: TimeSpan.FromSeconds(1))
    .WriteTo.Logger(l => l
        .Filter.ByExcluding(e => e.Level < LogEventLevel.Error)
        .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error))
        .WriteTo.File(
            Path.Combine(HttpContext.Current.Server.MapPath("~/logs/errors"), "log.txt"),
            rollingInterval: RollingInterval.Day,
            flushToDiskInterval: TimeSpan.FromSeconds(1))
    .CreateLogger();

我想要的是将错误警告日志事件级别分开。但是,我所有的 Error 日志仍会写入〜/ logs / warnings 文件夹。

Same question根本没有答案。

如何正确分离这些日志,配置有什么问题?

1 个答案:

答案 0 :(得分:0)

尝试使用此代码,它将错误和警告日志事件分开

Log.Logger = 
    new LoggerConfiguration()                 
        .MinimumLevel.Debug()                 
        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)                 
        .Enrich.FromLogContext()                 
        .WriteTo.Console()                 
        .WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)                     
        .WriteTo.File(@"Log\LogError.txt"))                 
        .WriteTo.Logger(lc => lc                     
        .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Warning)                     
        .WriteTo.File(@"Log\LogWarning.txt"))                 
        .WriteTo.File(@"Log\log.txt")                 
        .CreateLogger();