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

Azure Function V3中如何注入Serilog的ILogger?

在Azure Function中注入Serilog的ILogger替代Microsoft.Extensions.Logging的方法

你现在的问题核心是:Azure Functions默认会在Run方法参数中注入Microsoft.Extensions.Logging.ILogger,但你想直接使用Serilog本身的ILogger接口。要实现这个,我们需要通过构造函数注入来获取DI容器中的Serilog实例,而不是依赖函数绑定系统的参数注入。

步骤1:确保函数类是非静态的

首先,你的函数类已经是非静态的(public class XX),这很重要——静态类无法使用构造函数注入,所以必须保持非静态。

步骤2:通过构造函数注入Serilog的ILogger

修改你的函数类,添加私有字段存储Serilog的ILogger实例,并在构造函数中注入它:

using Serilog;
using Microsoft.Azure.WebJobs;

namespace LogFunction
{
    public class XX
    {
        // 私有字段存储Serilog的ILogger实例
        private readonly ILogger _serilogLogger;

        // 构造函数注入Serilog的ILogger
        public XX(ILogger logger)
        {
            _serilogLogger = logger;
        }

        [FunctionName("XX")]
        // 移除参数中的Microsoft.Extensions.Logging.ILogger
        public void Run([TimerTrigger("*/60 * * * * *")]TimerInfo myTimer)
        {
            var car = new { Make = "Honda", Model = "Civic" };
            // 使用Serilog的ILogger输出结构化日志
            _serilogLogger.Information("Log this object {Car}", car);
        }
    }
}

为什么不能直接在Run方法参数中用Serilog的ILogger?

Azure Functions的绑定系统会自动识别Microsoft.Extensions.Logging.ILogger类型并注入框架自带的日志实例,但它不会直接处理Serilog的ILogger接口。而你在Startup中通过AddSerilog已经将Serilog的ILogger注册到了DI容器,所以通过构造函数注入是最直接的获取方式。

验证你的Startup配置

你现有的Startup配置是正确的,它已经将Serilog集成到了Functions的日志系统中,并且会把Serilog的ILogger注入到DI容器:

var loggerConfiguration = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateLogger();
builder.Services.AddLogging(op => op.AddSerilog(loggerConfiguration));

如果你想要针对当前函数类的特定Logger(带类名上下文),也可以注入ILogger<XX>,这同样会是Serilog的实例,因为Serilog已经适配了Microsoft的日志抽象。

额外提示

  • 确保你已经安装了必要的NuGet包:Serilog.AspNetCore和Serilog.Extensions.Logging,这两个包是集成Serilog到Azure Functions的基础。
  • 运行函数后,你会看到日志通过Serilog输出到控制台,并且结构化日志的占位符(比如{Car})会正确序列化对象内容。

内容的提问来源于stack exchange,提问作者hello world

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:02:53