为何ASP.NET ILogger忽略我的日志级别设置?
Blazor Server中ILogger违反配置输出Debug日志问题排查
问题背景
你在Blazor Server应用中使用ASP.NET ILogger系统,相关代码及配置如下:
Program.cs中的日志初始化代码
using (var loggerFactory = LoggerFactory.Create(loggingBuilder => loggingBuilder .AddConfiguration(config) .AddJsonConsole() .AddDebug())) { logger = loggerFactory.CreateLogger<Program>(); } logger.LogInformation("Application starting up"); // some code // 开发环境下执行这段代码 if (builder.Environment.IsDevelopment()) { builder.Logging.ClearProviders(); builder.Logging.AddJsonConsole(); builder.Logging.AddDebug(); }
依赖注入使用Logger
private ILogger<AzureBlobService> Logger { get; }
appSettings.json日志配置
"Logging": { "LogLevel": { "Default": "Warning", "LouisHowe": "Information", "ThirdPartyServices": "Information", "CommonUtilities": "Information", "Microsoft": "Warning" }, "Debug": { "IncludeScopes": true }, "Console": { "FormatterName": "simple", "FormatterOptions": { "SingleLine": true, "IncludeScopes": true, "TimestampFormat": "HH:mm:ss ", "UseUtcTimestamp": true, "JsonWriterOptions": { "Indented": true } } } }
但实际收到了属于ThirdPartyServices.AzureStorage.AzureBlobService的Debug级日志:
{ "Timestamp": "23:28:31 ", "EventId": 0, "LogLevel": "Debug", "Category": "ThirdPartyServices.AzureStorage.AzureBlobService", "Message": "Creating container users-private with access None", "State": { "Message": "Creating container users-private with access None", "containerName": "users-private", "accessType": "None", "{OriginalFormat}": "Creating container {containerName} with access {accessType}" }, "Scopes": [] }
问题原因
核心问题出在开发环境的日志配置代码中:
- 你调用
builder.Logging.ClearProviders()清空所有日志提供者后,重新添加了AddJsonConsole()和AddDebug(),但没有重新加载appSettings.json中的日志配置。 - 此时新添加的日志提供者会使用默认日志级别(Debug提供者默认最低级别为Debug),完全忽略了你在appSettings.json中设置的
ThirdPartyServices: Information规则,导致Debug级日志被输出。
另外,你最初手动创建的LoggerFactory是局部实例,using块结束后会被释放,后续调用logger.LogInformation属于在已释放实例上操作,虽未引发错误,但属于不规范用法,建议统一通过依赖注入获取Logger实例。
解决方案
修改开发环境下的日志配置代码,重新绑定配置:
if (builder.Environment.IsDevelopment()) { builder.Logging.ClearProviders(); // 先添加配置绑定,再添加日志提供者 builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging")) .AddJsonConsole() .AddDebug(); }
这样新添加的日志提供者会读取appSettings.json中的LogLevel规则,ThirdPartyServices命名空间下的Debug级日志会被过滤,仅输出Information及以上级别的日志。
内容的提问来源于stack exchange,提问作者David Thielen
相关产品推荐
相关产品推荐

