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

Azure Function (Java) 如何向Log Analytics请求表CustomDimensions添加属性

在Java版Azure Function中给Log Analytics添加CustomDimensions的方法

我之前在Java Azure Function里也碰到过这个问题,一开始照着C#的思路套总是不行,后来摸索出几个靠谱的方案,分享给你:

1. 用TelemetryInitializer全局注入自定义维度

这和C#里的思路类似,但Java的实现细节不一样。你可以实现TelemetryInitializer接口,在初始化遥测数据的时候自动添加自定义属性:

首先写一个自定义的Initializer类:

import com.microsoft.applicationinsights.extensibility.TelemetryInitializer;
import com.microsoft.applicationinsights.telemetry.Telemetry;

public class CustomDimInitializer implements TelemetryInitializer {
    @Override
    public void initialize(Telemetry telemetry) {
        // 这里可以静态设置,也可以从环境变量/配置里读取动态值
        telemetry.getProperties().put("ServiceLine", "PaymentProcessing");
        telemetry.getProperties().put("Environment", System.getenv("AZURE_FUNCTIONS_ENVIRONMENT"));
    }
}

然后在你的Function类里注册这个Initializer,建议用@PostConstruct在函数初始化时完成注册:

import com.microsoft.applicationinsights.TelemetryClient;
import com.microsoft.applicationinsights.extensibility.TelemetryConfiguration;
import javax.annotation.PostConstruct;

public class PaymentFunction {
    private TelemetryClient telemetryClient;

    @PostConstruct
    public void setupTelemetry() {
        TelemetryConfiguration activeConfig = TelemetryConfiguration.getActive();
        activeConfig.getTelemetryInitializers().add(new CustomDimInitializer());
        telemetryClient = new TelemetryClient(activeConfig);
    }

    @FunctionName("ProcessPayment")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        // 发送自定义事件,会自动带上我们添加的维度
        telemetryClient.trackEvent("PaymentProcessed");
        context.getLogger().info("Payment processed successfully");
        return request.createResponseBuilder(HttpStatus.OK).body("Done").build();
    }
}

2. 直接在日志/遥测中添加临时维度

如果只是某些特定日志需要添加自定义属性,可以直接用TelemetryClient的API,或者结合SLF4J的MDC(如果用了日志框架的话):

方式A:用TelemetryClient直接添加

// 在函数方法里
Map<String, String> customProps = new HashMap<>();
customProps.put("PaymentId", "PAY-12345");
customProps.put("Amount", "99.99");
telemetryClient.trackTrace("Payment validated", SeverityLevel.Information, customProps);

方式B:用MDC自动同步到CustomDimensions

如果你的项目用了SLF4J(比如logback),可以把属性放到MDC里,Application Insights的日志适配器会自动把MDC的键值对同步到CustomDimensions:

import org.slf4j.MDC;

// 在函数逻辑里
MDC.put("PaymentId", "PAY-12345");
context.getLogger().info("Payment processed");
// 记得用完移除,避免线程复用导致属性串味
MDC.remove("PaymentId");

3. 通过host.json配置全局固定维度

如果有一些所有日志都需要带的固定属性,比如函数应用名称、团队名称,可以直接在host.json里配置,不用写代码:

{
  "applicationInsights": {
    "samplingSettings": {
      "isEnabled": true
    },
    "customDimensions": {
      "FunctionAppName": "PaymentProcessingApp",
      "Team": "PaymentTeam",
      "Environment": "%AZURE_FUNCTIONS_ENVIRONMENT%"
    }
  }
}

这里的%AZURE_FUNCTIONS_ENVIRONMENT%会自动读取环境变量的值,非常方便。

注意事项

  • 确保你的Function已经在Azure Portal里启用了Application Insights集成,配置好Connection String或者Instrumentation Key
  • 依赖方面,需要在pom.xml里添加applicationinsights-core和azure-functions-java-library的依赖,版本尽量用最新稳定版
  • 如果用MDC的话,要注意Azure Function的线程复用问题,记得及时清理MDC里的属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:15:57