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

如何在Spring Boot版Azure Function中实现Application Insights正确追踪关联?

解决Spring Boot Azure Functions在Application Insights中的调用链关联问题

问题根源

Azure Functions触发器会自动注入W3C TraceContext的traceparent头,但Spring Cloud Function Adapter与Application Insights Agent的自动 instrumentation未能在函数内部调用时正确传递trace上下文,导致两个请求的OperationId不一致,无法形成关联调用链。

解决方案

1. 手动传递Trace Context到内部调用

在发起内部函数调用(比如HelloWorldProducerTrigger调用FooProducerTrigger)时,主动获取当前请求的traceparent头,并将其作为请求头传递给目标函数:

使用WebClient的示例代码:

@FunctionName("HelloWorldProducerTrigger")
public ResponseEntity<String> helloWorld(
        @HttpTrigger(name = "req", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
        final ExecutionContext context) {

    // 获取当前请求的traceparent
    String traceParent = request.getHeaders().getFirst("traceparent");

    // 调用FooProducerTrigger时携带traceparent头
    WebClient webClient = WebClient.create();
    String response = webClient.post()
            .uri("http://localhost:7071/api/v2/foo") // 部署后替换为实际函数URL
            .header("traceparent", traceParent)
            .bodyValue("test payload")
            .retrieve()
            .bodyToMono(String.class)
            .block();

    return ResponseEntity.ok(response);
}

2. 配置Application Insights Agent增强上下文识别

在项目resources目录下创建applicationinsights.json配置文件,明确开启Azure Functions和HTTP请求的trace上下文传播:

{
  "connectionString": "${APPLICATIONINSIGHTS_CONNECTION_STRING}",
  "instrumentation": {
    "azureFunctions": {
      "enabled": true
    },
    "http": {
      "enabled": true,
      "traceContextPropagation": true
    },
    "springCloudFunction": {
      "enabled": true
    }
  }
}

3. 确保Maven打包与Agent加载正确

检查pom.xml中的maven-dependency-plugin配置,确保Agent被正确复制到构建目录:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <executions>
    <execution>
      <id>copy-agent</id>
      <phase>package</phase>
      <goals>
        <goal>copy</goal>
      </goals>
      <configuration>
        <artifactItems>
          <artifactItem>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>applicationinsights-agent</artifactId>
            <version>3.4.17</version> <!-- 使用最新稳定版 -->
            <outputDirectory>${project.build.directory}</outputDirectory>
            <destFileName>applicationinsights-agent.jar</destFileName>
          </artifactItem>
        </artifactItems>
      </configuration>
    </execution>
  </executions>
</plugin>

同时在Azure Functions的配置中添加JAVA_OPTS环境变量,值为-javaagent:applicationinsights-agent.jar,确保启动时加载Agent。

4. ServiceBus Trigger的上下文传递(针对ServiceBus场景)

如果涉及ServiceBus Trigger,发送消息时需将traceparent作为消息属性携带,接收时手动绑定上下文:

  • 发送消息:
String traceParent = request.getHeaders().getFirst("traceparent");
ServiceBusMessage message = new ServiceBusMessage("message payload");
message.addProperty("traceparent", traceParent);
serviceBusSender.send(message);
  • 接收消息并绑定上下文:
@FunctionName("FooProducerTrigger")
public void serviceBusProcess(
        @ServiceBusTrigger(name = "message", queueName = "foo-queue", connection = "ServiceBusConnection") ServiceBusMessage message,
        final ExecutionContext context) {

    String traceParent = message.getProperties().get("traceparent").toString();
    // 使用OpenTelemetry API设置当前trace上下文
    TraceContextData traceContext = TraceContextData.fromW3CString(traceParent);
    Context currentContext = Context.current().with(traceContext.getSpanContext());
    try (Scope scope = currentContext.makeCurrent()) {
        // 处理消息逻辑
        context.getLogger().info("Processing message with traceparent: " + traceParent);
    }
}

验证

部署后重新调用HelloWorldProducerTrigger,检查Application Insights端到端仪表盘中两个请求的OperationId是否一致,确认调用链已关联。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:10:37