问题描述
在使用 Azure API Management 时,常见的场景是客户端请求先经过 APIM 网关,再转发到后端服务 API。
当出现问题时,运维人员需要确认请求是否成功到达 APIM,以及是否被正确转发到后端服务。
然而,默认情况下,跨网关和后端的请求链路缺乏统一标识,导致排查困难。
为实现全链路跟踪,需要配置一个唯一 ID,使其在请求进入 APIM、转发到后端以及返回客户端时保持一致。
问题解答
在 APIM 中,可以通过 RequestId 实现唯一标识,并将其注入请求和响应的 Header,从而实现全链路跟踪。
具体步骤如下:
第一步:在 API Policy 中设置 Header
在 API 的 inbound、outbound 和 on-error 部分添加 set-header 策略,将 context.RequestId 写入自定义 Header(如 x-request-id):
<policies> <!-- Throttle, authorize, validate, cache, or transform the requests --> <inbound> <base /> <set-header name="x-request-id" exists-action="override"> <value>@(context.RequestId.ToString())</value> </set-header> </inbound> <!-- Control if and how the requests are forwarded to services --> <backend> <base /> </backend> <!-- Customize the responses --> <outbound> <base /> <set-header name="x-request-id" exists-action="override"> <value>@(context.RequestId.ToString())</value> </set-header> </outbound> <!-- Handle exceptions and customize error responses --> <on-error> <base /> <set-header name="x-request-id" exists-action="override"> <value>@(context.RequestId.ToString())</value> </set-header> </on-error> </policies>
第二步:启用诊断日志
在 APIM 的 Diagnostic settings 中配置日志,将 x-request-id 字段记录到 Azure Monitor 或 Log Analytics,以便后续查询。
第三步:客户端验证
配置完成后,客户端在响应 Header 中也能看到 x-request-id,通过该 ID 可以在日志中追踪请求的完整路径。
注意事项:
Correlation ID 虽然用于整体链路跟踪,但在 APIM 的 context 中无法直接获取,因此推荐使用 RequestId。
参考资料
Set header : https://learn.microsoft.com/en-us/azure/api-management/set-header-policy
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!