.NET 6 WebAPI:存在appsettings.json时控制器日志无法记录的疑问
问题场景
在.NET 6 WebAPI中,当项目包含如下配置的appsettings.json文件时:
{ "Logging": { "LogLevel": { "Default": "Information" } }, "AllowedHosts": "*" }
访问任意端点都不会记录控制器的活动日志,仅输出生命周期相关日志:
info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5237 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0] Content root path: C:\Temp\TestApps\Test1\SampleCCLogProviderApp\WebApplication5\WebApplication5\
但删除appsettings.json文件后,就能正常输出所有信息日志,包括控制器的活动日志:
info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5237 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0] Content root path: C:\Temp\TestApps\Test1\SampleCCLogProviderApp\WebApplication5\WebApplication5\ info: Microsoft.AspNetCore.Hosting.Diagnostics[1] Request starting HTTP/1.1 GET http://localhost:5237/weatherforecast - - info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0] Executing endpoint 'WebApplication5.Controllers.WeatherForecastController.Get (WebApplication5)' info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3] Route matched with {action = "Get", controller = "WeatherForecast"}. Executing controller action with signature System.Collections.Generic.IEnumerable`1[WebApplication5.WeatherForecast] Get() on controller WebApplication5.Controllers.WeatherForecastController (WebApplication5). info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1] Executing ObjectResult, writing value of type 'WebApplication5.WeatherForecast[]'. info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2] Executed action WebApplication5.Controllers.WeatherForecastController.Get (WebApplication5) in 64.1691ms info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1] Executed endpoint 'WebApplication5.Controllers.WeatherForecastController.Get (WebApplication5)' info: Microsoft.AspNetCore.Hosting.Diagnostics[2] Request finished HTTP/1.1 GET http://localhost:5237/weatherforecast - - - 200 - application/json;+charset=utf-8 192.2900ms
原因分析
这是.NET 6日志配置的默认逻辑导致的:
- 当项目没有自定义
appsettings.json时,框架会自动加载开发环境的默认日志配置,其中明确将Microsoft.AspNetCore系列命名空间的日志级别设为Information,因此能输出控制器相关的请求日志。 - 当你添加自定义
appsettings.json并仅设置Default日志级别时,会覆盖框架的默认配置。Default仅作用于未明确指定命名空间的日志类别,而控制器活动日志属于Microsoft.AspNetCore、Microsoft.AspNetCore.Mvc等特定命名空间,这些命名空间的日志级别在你的配置中未定义,会默认继承更严格的级别(通常为Warning及以上),所以不会输出Information级别的控制器日志。
解决方案
在appsettings.json的Logging.LogLevel节点中添加Microsoft.AspNetCore命名空间的日志级别配置即可恢复控制器日志输出:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Information" } }, "AllowedHosts": "*" }
内容的提问来源于stack exchange,提问作者Yogi
相关产品推荐
相关产品推荐

