问题描述
使用 Azure API Management(APIM)时,需要记录每个 API 请求的 Header 和 Body,以便进行问题排查和审计,如何配置才能完整捕获这些信息呢?
问题解答
在配置API的时候,启用 trace 策略来收集 inbound / outbound中分别收集请求的Header/Body信息。
具体操作步骤如下:
第一步:进入API的Policy编辑页面,分别修改Inbound和Outbound策略
在Inbound 加入 如下部分内容, 分别获取Request 的Headers 和 Body信息,作为Trace的Message内容
context.Request.Body.As<string>(preserveContent: true)
:用于读取请求体内容,并保留原始内容供后续处理。context.Request.Headers.Select(...)
:用于拼接所有请求头信息。
<inbound>
<base />
<trace source="request-info" severity="information">
<message>@{
var headerOutput = string.Join("\n", context?.Request?.Headers?.Select(h => $"{h.Key}: {string.Join(";", h.Value)}"));
var body = context?.Request?.Body?.As<string>(preserveContent: true) ?? "No Body";
return $"\n\nRequest Headers:\n{headerOutput}\n\nRequest Body:\n{body}\n\n";
}</message>
</trace>
</inbound>
在Outbound 加入 如下部分内容, 分别获取Response 的Headers 和 Body信息,作为Trace的Message内容
context.Response.Body.As<string>(preserveContent: true)
:用于读取响应体内容,并保留原始内容供后续处理。context.Response.Headers.Select(...)
:用于拼接所有响应的头信息。
<outbound>
<base />
<trace source="response-info" severity="information">
<message>@{
var headerOutput = string.Join("\n", context?.Response?.Headers?.Select(h => $"{h.Key}: {string.Join(";", h.Value)}"));
var body = context?.Response?.Body?.As<string>(preserveContent: true) ?? "No Body";
return $"\n\nResponse Headers:\n{headerOutput}\n\nResponse Body:\n{body}\n\n";
}</message>
</trace>
</outbound>
第二步:以AKS部署部署自建网关为例,查看日志输出效果
【end】
参考资料
将 Azure API 管理自承载网关部署到 Azure Kubernetes 服务 : https://docs.azure.cn/zh-cn/api-management/how-to-deploy-self-hosted-gateway-azure-kubernetes-service
Trace : https://docs.azure.cn/zh-cn/api-management/trace-policy