【Azure APIM】APIM的诊断日志与Application Insights的日志是否可以串联为一个端到端的日志链路呢?

问题描述

使用 Azure API Management(APIM)作为统一 API 网关,希望基于诊断日志(AzureDiagnostics表)中的日志数据,分析不同产品和服务之间的调用关系与性能指标。

**核心问题是:**如果注册在 APIM 上的所有 API 以及后端服务均已集成 Application Insights,是否可以通过 AzureDiagnostics 表中的 CorrelationId 字段作为 TraceId,将一次请求经过的所有服务串联起来,构建完整的端到端调用链路?

问题解答

可以,但CorrelationId本身不是最终的 TraceId,而是进入 Application Insights 调用链的入口。

真正能跨服务统一追踪的标识是 Application Insights 中的 operation_Id,两者之间存在一条固定的映射路径:

AzureDiagnostics.CorrelationId
        ↓
Application Insights requests 表 customDimensions["Request-Id"](值与 CorrelationId 相同)
        ↓
requests.operation_Id
        ↓
所有后端服务的 requests / dependencies / traces / exceptions

第一步:通过 CorrelationId 找到 operation_Id

AzureDiagnostics
| where ResourceType == "APIMANAGEMENT"
| where Category == "GatewayLogs"
| project TimeGenerated, CorrelationId, ApiId, ResponseCode, DurationMs
| join kind=inner (
    app('<your-appinsights-name>').requests
    | extend reqId = tostring(customDimensions["Request-Id"])
    | project reqId, operation_Id, duration, resultCode
) on $left.CorrelationId == $right.reqId
| project TimeGenerated, CorrelationId, operation_Id, ApiId, ResponseCode, DurationMs

第二步:用 operation_Id 拉取完整调用链

let targetCorrelationId = "<填入你的 CorrelationId>";
let opId = app('<your-appinsights-name>').requests
    | extend reqId = tostring(customDimensions["Request-Id"])
    | where reqId == targetCorrelationId
    | project operation_Id
    | take 1;
union
    app('<your-appinsights-name>').requests,
    app('<your-appinsights-name>').dependencies,
    app('<your-appinsights-name>').exceptions,
    app('<your-appinsights-name>').traces
| where operation_Id in (opId)
| project timestamp, itemType, cloud_RoleName, name, duration, success, operation_ParentId
| order by timestamp asc

注意:多个 Application Insights 实例时需要跨资源查询

若 APIM 与各后端服务使用不同的 Application Insights 实例,需在 union 中同时引用多个 app() 实例,否则即使 operation_Id 一致,跨实例的 Telemetry 数据也无法被查询到:

union
    app('apim-appinsights').requests,
    app('webapp-appinsights').requests,
    app('funcapp-appinsights').dependencies
| where operation_Id == "<your-operation-id>"
| order by timestamp asc

参考资料

如何将 Azure API 管理与 Azure 应用程序 Insights 集成 :https://learn.microsoft.com/zh-cn/azure/api-management/api-management-howto-app-insights?tabs=rest

应用程序映射:分类整理分布式应用程序 :https://learn.microsoft.com/zh-cn/azure/azure-monitor/app/app-map

AzureDiagnostics :https://learn.microsoft.com/zh-cn/azure/azure-monitor/reference/tables/azurediagnostics

在 Azure Monitor 中跨 Log Analytics 工作区、应用程序和资源查询数据 :https://learn.microsoft.com/zh-cn/azure/azure-monitor/logs/cross-workspace-query

正在加载评论...