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

如何为Application Insights配置Serilog自定义维度及排障

问题分析与解决

核心原因

你遇到的问题本质是ASP.NET Core内置日志系统和Serilog是两套独立的日志管道:

  • services.AddApplicationInsightsTelemetry()注册的是内置日志系统的Application Insights提供器,它只能读取内置日志框架的属性,无法识别Serilog特有的LogContext属性或消息模板里的自定义属性,所以这些属性不会出现在AI的customDimensions中。
  • 当你添加configuration.WriteTo.ApplicationInsights(...)时,是让Serilog直接把日志(包含所有自定义属性)写入AI,但此时内置日志的AI提供器还在工作,就会导致同一条日志被两个管道各记录一次,出现重复。

正确解决方案

方案一:禁用内置AI日志提供器,仅用Serilog写入AI

这是最简洁的方案,直接让Serilog全权负责日志输出到AI,避免重复:

  1. 修改Program.cs中的配置,调整AddApplicationInsightsTelemetry并保留Serilog的AI写入配置:
public static IHostBuilder CreateHostBuilder() =>
    new HostBuilder()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureAppConfiguration((_, _) => { })
        .UseSerilog((context, _, configuration) =>
        {
            configuration.MinimumLevel.Override("System", LogEventLevel.Information);
            configuration.MinimumLevel.Override("Microsoft", LogEventLevel.Information);
            configuration.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning);
            configuration.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning);
            configuration.ReadFrom.Configuration(context.Configuration);
            configuration.WriteTo.Console();
            configuration.Enrich.FromLogContext();
            // 保留Serilog直接写入AI的配置
            configuration.WriteTo.ApplicationInsights(
                context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"], 
                TelemetryConverter.Traces);
        })
        .ConfigureServices((context, services) =>
        {
            var configuration = context.Configuration;
            // 若需要Application Insights的其他功能(如性能监控),保留注册但禁用日志收集
            services.AddApplicationInsightsTelemetry(config =>
            {
                config.ConnectionString = configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
                // 禁用内置日志提供器的AI输出
                config.EnableLoggerTelemetry = false;
            });
            // 让内置日志使用Serilog(可选,适配其他地方的ILogger<T>调用)
            services.AddLogging(logBuilder => logBuilder.AddSerilog(dispose: true));
        });
  1. 你的MyClass.cs代码无需修改,不管是用LogContext.PushProperty还是消息模板{FunctionName}的方式,自定义属性都会被Serilog传递到AI的customDimensions中。

方案二:适配内置日志与Serilog的属性传递(不推荐)

如果一定要保留内置日志的AI提供器,需要额外做属性映射,但步骤繁琐且容易出问题,不如方案一直接高效。

验证效果

修改后,AI中的日志只会出现一次,且FunctionName等自定义属性会正常显示在customDimensions字段中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:03:34