ASP.NET Core拆分Serilog日志文件后ComponentSpace Trace不生效问题
问题根因
Serilog 中通过WriteTo:Logger声明的子 Logger 默认不会继承父级配置中的MinimumLevel:Override规则。你在根 Serilog 配置下给ComponentSpace指定的 Debug 级别仅对根 Logger 生效,子 Logger 没有匹配的规则,导致 ComponentSpace 输出的 Trace、Debug 级别的日志直接被过滤,无法写入拆分后的普通日志和错误日志文件。
解决方案
1. 调整Serilog配置
在每个子 Logger 的configureLogger节点下,补充和父级一致的 MinimumLevel 覆盖规则,修改后的完整配置如下:
"Serilog": { "MinimumLevel": { "Default": "Debug", "Override": { "Default": "Debug", "Microsoft": "Information", "Microsoft.Hosting.Lifetime": "Information", "ComponentSpace": "Debug" } }, "WriteTo": [ { "Name": "Logger", "Args": { "configureLogger": { "MinimumLevel": { "Default": "Debug", "Override": { "Microsoft": "Information", "Microsoft.Hosting.Lifetime": "Information", "ComponentSpace": "Debug" } }, "Filter": [ { "Name": "ByIncludingOnly", "Args": { "expression": "(@l in ['Error', 'Fatal', 'Warning'])" } } ], "WriteTo": [ { "Name": "File", "Args": { "path": "Logs/WebApp/Errors/error_.log", "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}", "rollingInterval": "Day" } } ] } } }, { "Name": "Logger", "Args": { "configureLogger": { "MinimumLevel": { "Default": "Debug", "Override": { "Microsoft": "Information", "Microsoft.Hosting.Lifetime": "Information", "ComponentSpace": "Debug" } }, "Filter": [ { "Name": "ByIncludingOnly", "Args": { "expression": "(@l in ['Information', 'Debug'])" } } ], "WriteTo": [ { "Name": "File", "Args": { "path": "Logs/WebApp/Informations/log_.log", "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}", "rollingInterval": "Day" } } ] } } } ], "Enrich": [ "FromLogContext", "WithMachineName" ], "Properties": { "Application": "MultipleLogFilesSample" } }
2. 校验配置加载逻辑
确认两点:
- 自定义JSON文件中,上述Serilog配置的层级和代码中指定的加载节点
WebApp:Logger匹配,即完整路径为WebApp:Logger:Serilog,否则配置不会被正确读取 - 加载自定义JSON文件时确认文件路径读取正确,避免配置加载失败
验证方法
可先在根 Serilog 配置的WriteTo节点下临时添加控制台输出:
{"Name": "Console"}
启动程序后查看控制台是否有ComponentSpace的相关日志输出,确认日志生成正常后再验证拆分后的文件写入逻辑即可。
内容的提问来源于stack exchange,提问作者Dah Sra
相关产品推荐
相关产品推荐

