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

Azure Function中ILogger日志仅在Live Metrics,未同步到Transaction Search

问题:Azure Function构造注入ILogger的自定义日志不显示在Transaction Search中

问题详情

发布Azure Function后,已成功连接Application Insights:

  • Transaction Search中能看到部分系统日志,但构造注入ILogger输出的自定义追踪日志缺失
  • 这些自定义日志可正常显示在Live Metrics中
  • 仅当将ILogger作为方法参数注入时,日志才会出现在Transaction Search中

注:为复用ILogger采用构造函数注入方式,代码中实际包含Startup配置(与最初计划的无Startup/IServiceCollection不符)。

代码片段

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

namespace AFLeaderListFunc
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddLogging();
            builder.Services.AddTransient<Function1>();
        }
    }
    public class Function1
    {
        private readonly ILogger _logger;

        public Function1(ILogger<Function1> logger)
        {
            _logger = logger;
        }


        [FunctionName("Function1")]
        public async Task Run([TimerTrigger("0 05 13 * * *")] TimerInfo myTimer)
        {
            try
            {
                _logger.LogInformation("Test using DI injection");
                _logger.LogInformation(await GetADUserAsyncByEmail());
                _logger.LogInformation("Executing complete");
                _logger.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.ToString());
                Console.WriteLine(ex);
            }
        }
    }
}

.csproj配置

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
  </PropertyGroup>

    <ItemGroup>
    <PackageReference Include="Azure.Identity" Version="1.8.1" />
    <PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.4.0" />
    <PackageReference Include="Dapper" Version="2.0.123" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.20.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.15.0" />
    <PackageReference Include="Microsoft.AspNetCore.AzureKeyVault.HostingStartup" Version="2.0.4" />
    <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="3.1.32" />
    <PackageReference Include="Microsoft.Graph" Version="4.52.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.1.1" />
    <PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
    <PackageReference Include="System.Text.Encodings.Web" Version="6.0.0" />
  </ItemGroup>
    <ItemGroup>
        <FunctionsPreservedDependencies Include="System.Text.Encodings.Web.dll" />
    </ItemGroup>
  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <None Update="host.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

核心原因分析

  1. 上下文关联缺失:方法参数注入的ILogger会自动绑定当前Function执行的Operation ID,而构造注入的实例在初始化时未获取到该上下文,导致日志无法关联到Transaction追踪链,因此Transaction Search无法筛选到这些日志(Live Metrics不依赖严格上下文关联,所以能显示)。
  2. 依赖包版本冲突:Microsoft.ApplicationInsights.WorkerService(2.15.0)与Microsoft.ApplicationInsights(2.20.0)版本差异过大,可能导致上下文传递逻辑异常。
  3. 日志配置缺失:host.json未明确配置Application Insights的日志过滤规则,可能导致部分日志类别或级别被过滤。

排查与修复步骤

1. 手动绑定Operation ID到构造注入的ILogger

注入IOperationIdProvider,为日志添加Operation ID标记,确保关联到Transaction追踪链:

private readonly ILogger _logger;
private readonly string _operationId;

public Function1(ILogger<Function1> logger, IOperationIdProvider operationIdProvider)
{
    _logger = logger;
    _operationId = operationIdProvider.GetOperationId();
}

// 日志输出时携带Operation ID
_logger.LogInformation("Test using DI injection {OperationId}", _operationId);

2. 统一Application Insights依赖包版本

将Microsoft.ApplicationInsights.WorkerService升级至与Microsoft.ApplicationInsights一致的版本(如2.20.0),避免版本冲突:

<PackageReference Include="Microsoft.ApplicationInsights" Version="2.20.0" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.20.0" />

3. 配置host.json日志规则

添加Application Insights日志配置,确保自定义日志被正确采集:

{
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      },
      "enableLiveMetricsFilters": true
    },
    "logLevel": {
      "AFLeaderListFunc.Function1": "Information",
      "Default": "Information"
    }
  }
}

4. 简化Startup配置

移除不必要的builder.Services.AddLogging()(Azure Functions宿主已默认配置日志系统):

public override void Configure(IFunctionsHostBuilder builder)
{
    builder.Services.AddTransient<Function1>();
}

内容的提问来源于stack exchange,提问作者Alexander Thomsen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:18:08