【Azure APIM】自建網(wǎng)關(guān)(self-host gateway)收集請求的Header和Body內(nèi)容到日志中的辦法
問題描述
使用 Azure API Management(APIM)時(shí),需要記錄每個(gè) API 請求的 Header 和 Body,以便進(jìn)行問題排查和審計(jì),如何配置才能完整捕獲這些信息呢?
問題解答
在配置API的時(shí)候,啟用 trace 策略來收集 inbound / outbound中分別收集請求的Header/Body信息。
具體操作步驟如下:
第一步:進(jìn)入API的Policy編輯頁面,分別修改Inbound和Outbound策略
在Inbound 加入 如下部分內(nèi)容, 分別獲取Request 的Headers 和 Body信息,作為Trace的Message內(nèi)容
context.Request.Body.As<string>(preserveContent: true):用于讀取請求體內(nèi)容,并保留原始內(nèi)容供后續(xù)處理。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 加入 如下部分內(nèi)容, 分別獲取Response 的Headers 和 Body信息,作為Trace的Message內(nèi)容
context.Response.Body.As<string>(preserveContent: true):用于讀取響應(yīng)體內(nèi)容,并保留原始內(nèi)容供后續(xù)處理。context.Response.Headers.Select(...):用于拼接所有響應(yīng)的頭信息。
<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部署部署自建網(wǎng)關(guān)為例,查看日志輸出效果

【end】
參考資料
將 Azure API 管理自承載網(wǎng)關(guān)部署到 Azure Kubernetes 服務(wù) : 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
當(dāng)在復(fù)雜的環(huán)境中面臨問題,格物之道需:濁而靜之徐清,安以動(dòng)之徐生。 云中,恰是如此!

浙公網(wǎng)安備 33010602011771號