【Azure APIM】自建网关(self‐host gateway)收集请求的Header和Body内容到日志中的办法 - LuBu0505/My-Code GitHub Wiki
使用 Azure API Management(APIM)时,需要记录每个 API 请求的 Header 和 Body,以便进行问题排查和审计,如何配置才能完整捕获这些信息呢?
在配置API的时候,启用 trace 策略来收集 inbound / outbound中分别收集请求的Header/Body信息。
具体操作步骤如下:
在Inbound 加入 如下部分内容, 分别获取Request 的Headers 和 Body信息,作为Trace的Message内容
-
context.Request.Body.As<string>(preserveContent: true)
:用于读取请求体内容,并保留原始内容供后续处理。 -
context.Request.Headers.Select(...)
:用于拼接所有请求头信息。
@{
var headerOutput = string.Join("\n", context?.Request?.Headers?.Select(h => $"{h.Key}: {string.Join(";", h.Value)}"));
var body = context?.Request?.Body?.As(preserveContent: true) ?? "No Body";
return $"\n\nRequest Headers:\n{headerOutput}\n\nRequest Body:\n{body}\n\n";
}
在Outbound 加入 如下部分内容, 分别获取Response 的Headers 和 Body信息,作为Trace的Message内容
-
context.Response.Body.As<string>(preserveContent: true)
:用于读取响应体内容,并保留原始内容供后续处理。 -
context.Response.Headers.Select(...)
:用于拼接所有响应的头信息。
@{
var headerOutput = string.Join("\n", context?.Response?.Headers?.Select(h => $"{h.Key}: {string.Join(";", h.Value)}"));
var body = context?.Response?.Body?.As(preserveContent: true) ?? "No Body";
return $"\n\nResponse Headers:\n{headerOutput}\n\nResponse Body:\n{body}\n\n";
}
【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
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!