You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Serilog如何按SourceContext基类排除日志事件?求临时方案

Serilog按基类过滤日志的临时解决办法

临时解决办法1:直接编写过滤委托

可以在Filter.ByExcluding中直接实现逻辑,检查日志事件的SourceContext对应的类型是否派生自目标基类:

.Filter.ByExcluding(logEvent => 
{
    // 尝试获取SourceContext属性
    if (!logEvent.Properties.TryGetValue("SourceContext", out var sourceContextValue))
        return false;
    
    // 去除字符串两端的引号,得到完整类型名
    var sourceContext = sourceContextValue.ToString().Trim('"');
    // 解析类型
    var loggerType = Type.GetType(sourceContext);
    
    // 检查类型是否派生自Animal基类
    return loggerType != null && typeof(Animal).IsAssignableFrom(loggerType);
})

临时解决办法2:封装成扩展方法复用

如果需要多次使用按基类过滤的逻辑,可以封装成扩展方法,模拟你想要的FromAssignableSource用法:

public static class SerilogMatchingExtensions
{
    public static Func<LogEvent, bool> FromAssignableSource<TBase>()
    {
        var baseType = typeof(TBase);
        
        return logEvent => 
        {
            if (!logEvent.Properties.TryGetValue("SourceContext", out var sourceContextValue))
                return false;
            
            var sourceContext = sourceContextValue.ToString().Trim('"');
            var loggerType = Type.GetType(sourceContext);
            
            return loggerType != null && baseType.IsAssignableFrom(loggerType);
        };
    }
}

使用时和你期望的语法一致:

.Filter.ByExcluding(SerilogMatchingExtensions.FromAssignableSource<Animal>())

注意事项

  • 确保SourceContext对应的是完整类型名(包含命名空间),Serilog默认创建的日志器会自动使用完整类型名作为SourceContext;
  • 如果你的类型来自外部程序集,Type.GetType可能需要传入包含程序集信息的类型名(比如"MyAssembly.Animal, MyAssembly"),或者根据实际情况调整类型解析逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:32:32