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

依赖注入的ILogger<T>无法输出日志,问题出在哪?

问题原因与修复方案

核心问题:重复调用AddLogging覆盖了日志配置

你在Startup.Configure里分三次调用builder.Services.AddLogging(),每次调用都会生成一个全新的日志构建器,前两次添加的Console、Debug日志输出源会被第三次调用完全覆盖,最终只保留了日志级别设置,却没有实际的输出渠道,所以构造注入的ILogger<InProcSO>无法把日志输出到控制台。

而Run方法参数里的ILogger是Azure Functions运行时直接注入的实例,它用的是Functions自带的默认日志配置,不受你错误的AddLogging调用影响,所以能正常输出。

正确的配置写法

把三次AddLogging合并成一次链式调用,让所有配置都作用在同一个日志构建器上:

[assembly: FunctionsStartup(typeof(Playground.Startup))]

namespace Playground
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddLogging(logging => 
            {
                logging.AddConsole();
                logging.AddDebug();
                logging.SetMinimumLevel(LogLevel.Debug);
            });
        }
    }
    
    public class InProcSO
    {
        private readonly ILogger<InProcSO> _logger;

        public InProcSO(ILogger<InProcSO> log)
        {
            _logger = log;
        }

        [FunctionName(nameof(InProcSO))]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger logger)
        {
            _logger.LogInformation("works not");
            logger.LogInformation("works");

            return new OkObjectResult("OK");
        }
    }
}

额外提示

Azure Functions本身已经默认配置了Console等日志输出源,除非你需要自定义日志行为(比如接入第三方日志库、精细化调整日志级别),否则其实没必要在Startup里手动配置AddLogging。如果只是想调整日志级别,推荐通过host.json文件配置,更符合Functions的规范:

{
  "logging": {
    "logLevel": {
      "Playground.InProcSO": "Debug"
    },
    "console": {
      "isEnabled": true
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:55:17