请求Azure告警邮件中获取失败API详情的自定义Webhook实现指引
实现Azure APIM失败API告警邮件包含详细信息的方案
1. 确保AppInsights采集到API关键详情字段
先在APIM中配置策略,将API名称、请求体、响应体等核心字段记录到AppInsights,示例策略如下:
<policies> <inbound> <!-- 保存请求体到变量 --> <set-variable name="requestBody" value="@(context.Request.Body.As<string>(preserveContent: true))" /> </inbound> <backend> <forward-request /> </backend> <outbound> <!-- 保存响应体到变量 --> <set-variable name="responseBody" value="@(context.Response.Body.As<string>(preserveContent: true))" /> <!-- 将详情追踪到AppInsights --> <trace source="APIM-Failure-Details" severity="Information"> @(new JObject( new JProperty("ApiName", context.Api.Name), new JProperty("RequestBody", context.Variables["requestBody"]), new JProperty("ResponseBody", context.Variables["responseBody"]), new JProperty("ApiPath", context.Request.Url.Path), new JProperty("StatusCode", context.Response.StatusCode) ).ToString()) </trace> </outbound> <on-error> <!-- 错误场景下记录详情 --> <trace source="APIM-Error-Details" severity="Error"> @(new JObject( new JProperty("ApiName", context.Api.Name), new JProperty("RequestBody", context.Variables.ContainsKey("requestBody") ? context.Variables["requestBody"] : "N/A"), new JProperty("ResponseBody", context.Response.Body.As<string>(preserveContent: true)), new JProperty("ApiPath", context.Request.Url.Path), new JProperty("StatusCode", context.Response.StatusCode), new JProperty("ErrorMessage", context.LastError.Message) ).ToString()) </trace> </on-error> </policies>
2. 编写AppInsights告警查询,返回所需详情
调整告警的Kusto查询,确保返回所有需要的字段,示例查询:
requests | where success == false | where timestamp > ago(5m) <!-- 按需调整时间范围 --> | extend ApiName = tostring(customDimensions["ApiName"]) | extend RequestBody = tostring(customDimensions["RequestBody"]) | extend ResponseBody = tostring(customDimensions["ResponseBody"]) | extend ApiPath = tostring(customDimensions["ApiPath"]) | project ApiName, ApiPath, RequestBody, ResponseBody, StatusCode = resultCode, Timestamp = timestamp, OperationId = operation_Id
3. 配置自定义Webhook的负载模板
在告警规则的「操作组」中添加自定义Webhook,使用以下模板生成包含详情的负载:
{ "alert_rule_name": "#alertrulename", "alert_trigger_time": "#alertcontext.starttime", "total_failed_count": "#alertcontext.count", "failed_api_details": [ #foreach($row in $alertcontext.searchresult) { "api_name": "$row.ApiName", "api_path": "$row.ApiPath", "request_body": "$row.RequestBody", "response_body": "$row.ResponseBody", "status_code": "$row.StatusCode", "failure_time": "$row.Timestamp", "operation_id": "$row.OperationId" }#if($foreach.hasNext),#end #end ] }
关键说明:
#alertcontext.searchresult:对应告警查询返回的所有结果行,通过foreach循环遍历每一行数据$row.字段名:直接引用Kusto查询中project定义的字段名称,需完全一致- 特殊字符处理:如果请求/响应体包含双引号或换行,可在Kusto查询中用
replace_string(RequestBody, '"', '\\"')做转义,避免JSON格式错误
4. 接收Webhook并生成邮件
部署简单的Web服务(如Azure Function、Logic App)接收Webhook请求,将负载中的详情格式化后发送邮件。比如用Logic App,可直接解析JSON负载,再通过「发送电子邮件」动作将详情插入邮件内容。
内容的提问来源于stack exchange,提问作者Snehasis Panda
相关产品推荐
相关产品推荐

