Azure APIM自定义策略预检查失败时记录至App Insight咨询
在Azure APIM中直接将预检查失败日志写入App Insights的方案
没问题,你完全可以跳过Event Hub,直接利用APIM内置的log-to-appinsights策略实现预检查失败时的日志记录需求,下面是具体的实现步骤和示例:
前提准备
首先确保你的APIM实例已经关联了App Insights资源:
- 登录Azure门户,进入你的APIM实例
- 切换到「监测」->「Application Insights」页面
- 关联已有的App Insights资源,或者创建新的资源(关联后APIM会自动获得向其发送日志的权限)
自定义策略实现
你可以在预检查逻辑的失败分支中,先调用log-to-appinsights记录详细信息,再返回错误响应。以下是完整的策略示例:
<policies> <inbound> <base /> <!-- 示例:检查请求是否包含必填的验证头 --> <choose> <when condition="@(!context.Request.Headers.ContainsKey("X-Validation-Token"))"> <!-- 记录预检查失败日志到App Insights --> <log-to-appinsights> <message>Pre-check failed: Missing required X-Validation-Token header</message> <severity>Error</severity> <!-- 添加自定义属性,方便后续分析查询 --> <properties> <property name="RequestId" value="@context.RequestId" /> <property name="ClientIpAddress" value="@context.Request.IpAddress" /> <property name="RequestPath" value="@context.Request.Url.Path" /> <property name="Timestamp" value="@DateTime.UtcNow.ToString("o")" /> </properties> </log-to-appinsights> <!-- 返回错误响应给客户端 --> <return-response> <set-status code="400" reason="Bad Request" /> <set-body>{"errorCode": "VALIDATION_FAILED", "message": "Missing required X-Validation-Token header"}</set-body> <set-header name="Content-Type" exists-action="override"> <value>application/json</value> </set-header> </return-response> </when> </choose> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error> </policies>
关键细节说明
log-to-appinsights策略:这是APIM专门用于直接向关联的App Insights发送日志的内置策略,无需经过Event Hub中转。你可以自定义日志消息、严重级别(Trace/Information/Warning/Error/Critical),还能添加自定义属性来丰富日志维度。- 动态日志内容:可以使用APIM表达式动态生成日志内容,比如记录请求参数、用户身份信息等(注意不要记录敏感数据,如密码、令牌内容)。
- 日志查询:日志写入App Insights后,你可以在App Insights的「日志」页面使用Kusto查询语句筛选分析,比如:
traces | where message contains "Pre-check failed" | project timestamp, message, customDimensions.RequestId, customDimensions.ClientIpAddress
额外提示
如果你的预检查逻辑比较复杂,也可以把日志记录逻辑封装到<set-variable>或者自定义策略片段中,提高代码复用性。
内容的提问来源于stack exchange,提问作者krishnakumar
相关产品推荐
相关产品推荐

