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

Azure Functions Isolated中CustomDimensions未在Application Insights追踪中显示

Azure Functions日志CustomDimensions不显示的问题解决

问题分析

你尝试的两种方式存在以下问题:

  1. BeginScope方式:默认情况下,Application Insights Worker Service未开启Scope属性收集,导致Scope中的自定义属性无法进入CustomDimensions。
  2. 直接传字典作为args参数:Log方法的params object[] args是用来填充日志模板中的占位符(如{method}),并非用来添加自定义维度,这种用法会导致字典被当作普通参数处理,而非属性。

正确解决方案

方案一:修复BeginScope配置(适用于单条/范围日志)

在服务配置中开启Scope属性收集,确保BeginScope中的属性能被Application Insights捕获:

.ConfigureServices((hostContext, services) =>
{
    services.AddApplicationInsightsTelemetryWorkerService(options =>
    {
        options.EnableScopes = true; // 关键:开启Scope属性收集
    });
    services.ConfigureFunctionsApplicationInsights();
})

保留你最初的BeginScope实现代码即可,此时单条日志会带上TraceType维度。

方案二:直接为单条日志添加自定义维度(无需Scope)

通过扩展方法为单条日志绑定属性,避免范围影响:

public static void LogCustomTrace(this ILogger logger,
            string method,
            string message,
            TraceType traceType,
            LogLevel logLevel = LogLevel.Information,
            Exception? exception = null,
            params object[] args)
{
    // 格式化带参数的消息
    var formattedMessage = string.Format(message, args);
    
    // 用BeginScope包裹单条日志,仅为该条日志添加属性
    using (logger.BeginScope(new Dictionary<string, object> { ["TraceType"] = traceType.ToString() }))
    {
        if (exception != null)
        {
            logger.Log(logLevel, exception, "[{Method}]: {Message}", method, formattedMessage);
        }
        else
        {
            logger.Log(logLevel, "[{Method}]: {Message}", method, formattedMessage);
        }
    }
}

额外检查项

  1. 确认连接字符串:确保函数应用配置了正确的APPLICATIONINSIGHTS_CONNECTION_STRING(本地在local.settings.json,Azure门户在配置项中)。
  2. 日志级别配置:在host.json中确保日志级别不低于你使用的logLevel,例如:
{
  "logging": {
    "applicationInsights": {
      "logLevel": {
        "Default": "Information"
      }
    },
    "logLevel": {
      "Default": "Information"
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:27:05