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

如何用Serilog实现Http日志文件存Info、数据库存Warning?

解决方案

要实现这个需求,核心是给Serilog的不同输出Sink(文件、数据库)单独配置过滤规则,让它们各自处理不同级别的目标日志,具体修改如下:

修改后的Serilog配置

"Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": {
        "Default": "Debug",
        "Override": {
            "Microsoft.AspNetCore": "Warning",
            "Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"
        }
    },
    "WriteTo": [
        { "Name": "Console" },
        {
            "Name": "File",
            "Args": {
                "path": "Logs/log.txt",
                "rollingInterval": "Day"
            }
        },
        {
            "Name": "MSSqlServer",
            "Args": {
                "connectionString": "....",
                "restrictedToMinimumLevel": "Information",
                "filter": "!(SourceContext = 'Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware' && Level = 'Information')"
                // 其他配置项保留
            }
        }
    ]
}

关键说明

  • 全局MinimumLevel.Override保持不变,确保File Sink能接收到HttpLoggingMiddleware的Info级别日志。
  • 给MSSqlServer Sink添加filter参数,用Serilog表达式过滤掉该中间件的Info日志:
    • SourceContext = 'Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware' 定位目标中间件的日志
    • Level = 'Information' 匹配Info级别
    • 前面加!表示排除这类日志,最终数据库只会写入该中间件Warning及以上级别的日志,同时不影响其他日志的正常写入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 16:13:21