You need to enable JavaScript to run this app. Serilog多sink配置下按SpecialEvent属性过滤写入异常排查
优惠活动
大模型
产品
解决方案
定价
更多

Serilog多sink配置下按SpecialEvent属性过滤写入异常排查

问题原因&解决方案

核心问题点

  • 断言方法isSpecialEventPresent逻辑写反:当存在非空SpecialEvent属性时,你当前返回的是string.IsNullOrWhiteSpace(eventVal.ToString()),也就是属性值非空时返回false,属性为空时才返回true,和需求的判断逻辑完全相反。
  • 数据库Sink配置错误:你当前的子Logger配置仅加了过滤规则,没有指定写入ApplicationDatabase的逻辑,同时保留了根配置里直接声明的logConfig.WriteTo.ApplicationDatabase(connectionString),导致所有日志不受过滤限制直接写入数据库。
  • 单Sink过滤规则配置方式错误:直接跟在WriteTo.File()后的Filter是作用于全局根Logger的,并非仅对File Sink生效,过滤规则不生效。

修正后的代码

1. 修正断言方法逻辑

private bool isSpecialEventPresent(LogEvent le)
{
    if (le.Properties.TryGetValue("SpecialEvent", out LogEventPropertyValue eventVal) 
        && eventVal is ScalarValue scalarVal
        && scalarVal.Value != null)
    {
        // 存在非空SpecialEvent属性时返回true
        return !string.IsNullOrWhiteSpace(scalarVal.Value.ToString());
    }
    return false;
}

2. 修正Sink配置

首先删掉根配置中原来直接声明的logConfig.WriteTo.ApplicationDatabase(connectionString),改用子Logger分别给两个Sink加独立过滤规则:

logConfig
    // 数据库Sink:仅写入带非空SpecialEvent的日志
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(le => isSpecialEventPresent(le))
        .WriteTo.ApplicationDatabase(connectionString))
    // 文件Sink:仅写入不带SpecialEvent的日志
    .WriteTo.Logger(lc => lc
        .Filter.ByExcluding(le => isSpecialEventPresent(le))
        .WriteTo.File(@".\logs\LocalFile.log"));

内容的提问来源于stack exchange,提问作者Newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 11:12:03