【Azure API 管理】在APIM 中添加 log-to-eventhub 策略,把 Request Body 信息全部记录在Event Hub中

简介: 【Azure API 管理】在APIM 中添加 log-to-eventhub 策略,把 Request Body 信息全部记录在Event Hub中

问题描述

根据文档 https://docs.azure.cn/zh-cn/api-management/api-management-howto-log-event-hubs , 可以将Azure API Management中的请求记录到Azure 事件中心。文档中有详细的步骤描述。但是在对于如何创建APIM的Logger, 如何在API中配置策略描述非常不清楚,所以本文就补充如何创建Logger及在APIM的API中添加log-to-eventhub 策略。

前提条件

 

操作步骤

1) 创建APIM Logger

示例

PUT https://management.chinacloudapi.cn/subscriptions/<your subscription id>/resourceGroups/<group name>/providers/Microsoft.ApiManagement/service/<your apim name>/loggers/<loggerideh01>?api-version=2020-12-01

注:替换<>中的内容为自己的相应资源信息,同时也定义loggers的名称。

      这里的Endpoint为中国区Azure的Endpoint: https://management.chinacloudapi.cn/, 如果需要Global Azure,则为:https://management.azure.com/

Authorization

两种方式任选其一:

  1. Azure Active Directory OAuth2 Flow :  https://www.cnblogs.com/lulight/p/14279338.html
  2. 似乎用浏览器打开Azure APIM的门户,通过F12--开发者选项中的 Network, 查看其中对API的请求,复制其中的Authorization 值

 

 

Body

{
  "properties": {
    "loggerType": "azureEventHub",
    "description": "adding a new logger",
    "credentials": {
      "name": "<your event hub name>",
      "connectionString": "Endpoint=sb://<your event hub namespace>.servicebus.chinacloudapi.cn/;SharedAccessKeyName=xxxxxxxxxxxxxxxxx;SharedAccessKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    }
  }
}

 

Response - 201 Created

{
    "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxx-rg/providers/Microsoft.ApiManagement/service/xxxx/loggers/loggerideh01",
    "type": "Microsoft.ApiManagement/service/loggers",
    "name": "loggerideh01",
    "properties": {
        "loggerType": "azureEventHub",
        "description": "adding a new logger",
        "credentials": {
            "name": "xxxxxxxxxxxx",
            "connectionString": "{{Logger-Credentials--xxxxxxxxxxxx}}"
        },
        "isBuffered": true,
        "resourceId": null
    }
}

演示动画

 

2) 添加 log-to-eventhub 策略

  1. 浏览到自己的 APIM 实例。
  2. 选择“API”选项卡。
  3. 选择要将策略添加到的 API。
  4. 选择“所有操作”。
  5. 选择屏幕顶部的“设计”选项卡。
  6. 在“入站或出站处理”窗口中,单击三角形(铅笔旁边)。
  7. 选择“代码编辑器”。 有关详细信息,请参阅如何设置或编辑策略
  8. 将光标放在 inboundoutbound 策略部分中。
  9. 在右侧窗口中,选择“高级策略” > “记录到 EventHub”。 这会插入 log-to-eventhub 策略语句模板。

 

注: Log-to-eventhub 中的logger-id由上面第一步创建。 Request Body的信息一定要进行格式转换。所以需要使用   context.Request.Body.As<string>()

<policies>
    <inbound>
        <base />
        <log-to-eventhub logger-id="loggerideh01">@{
        return new JObject(
            new JProperty("EventTime", DateTime.UtcNow.ToString()),
            new JProperty("ServiceName", context.Deployment.ServiceName),
            new JProperty("RequestId", context.RequestId),
            new JProperty("RequestBody1", context.Request.Body.As<string>()),
            new JProperty("OperationName", context.Operation.Name)
        ).ToString();
    }</log-to-eventhub>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
        <log-to-eventhub logger-id="loggerideh01">@{
        return new JObject(
            new JProperty("EventTime", DateTime.UtcNow.ToString()),
            new JProperty("ServiceName", context.Deployment.ServiceName),
            new JProperty("RequestId", context.RequestId),
            new JProperty("RequestBody2", context.Response.Body.As<string>()),
            new JProperty("OperationName", context.Operation.Name)
        ).ToString();
    }</log-to-eventhub>
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

 

 

3) 连接到Event Hub,查看 Request Body 信息

下载zip包,解压后在里面找到文件名为:ServiceBusExplorer.exe。 双击即可运行

 

 

在下面的字符串框中输入Event Hub Namespace的连接字符串。点击Save/ OK后,即可连接到Event Hub中。

 

 

进入保存日志的Event Hub中,找到合适的分区数,点击“Create Partitions Listener ”, 然后再弹出的页面中点击 “Strat”按钮,就可以收到Event Hub中所存储的消息

 

附录一:如何在APIM的Policy set-variable 中为参数在进行格式转换时候进行验证是否为null呢?避免Expression evaluation failed.

使用C#的问号表达式 (condition == null ? value1 :value2)

在APIM中,如果在测试阶段,出现Expression evaluation failed错误,可以在Test 的Trace中进行查看,了解真实的错误信息。如:

{
                "source": "log-to-eventhub",
                "timestamp": "2021-12-01T03:25:33.7362765Z",
                "elapsed": "00:00:00.0007502",
                "data": {
                    "messages": [
                        {
                            "message": "Expression evaluation failed.",
                            "expression": "\n        return new JObject(\n            new JProperty(\"EventTime\", DateTime.UtcNow.ToString()),\n            new JProperty(\"ServiceName\", context.Deployment.ServiceName),\n            new JProperty(\"RequestId\", context.RequestId),\n            new JProperty(\"RequestIp\", context.Request.Body),\n            new JProperty(\"OperationName\", context.Operation.Name)\n        ).ToString();\n    ",
                            "details": "Could not determine JSON object type for type Microsoft.WindowsAzure.ApiManagement.Proxy.Gateway.MessageBody.\r\n   at Newtonsoft.Json.Linq.JValue.GetValueType(Nullable`1 current, Object value)\r\n   at Newtonsoft.Json.Linq.JContainer.CreateFromContent(Object content)\r\n   at Newtonsoft.Json.Linq.JProperty..ctor(String name, Object content)"
                        },
                        "Expression evaluation failed. Could not determine JSON object type for type Microsoft.WindowsAzure.ApiManagement.Proxy.Gateway.MessageBody.\r\n   at Newtonsoft.Json.Linq.JValue.GetValueType(Nullable`1 current, Object value)\r\n   at Newtonsoft.Json.Linq.JContainer.CreateFromContent(Object content)\r\n   at Newtonsoft.Json.Linq.JProperty..ctor(String name, Object content)",
                        "Could not determine JSON object type for type Microsoft.WindowsAzure.ApiManagement.Proxy.Gateway.MessageBody."
                    ]
                }
            }

为了避免这样的情况,在格式转换时候,最好对其进行 null 检测,当时 null的时候就可以改变其值的或者赋值为“”。

 

 <set-variable name="testvalue" value="@(context.Variables["tokenvalue"]==null?context.Request.Headers.GetValueOrDefault("User-Agent","empty"):"")" />

 <set-variable name="requestbody" value="@(context.Request.Body==null?"no body":context.Request.Body.As<string>())" />

 

 

参考资料

如何在 Azure API 管理中将事件记录到 Azure 事件中心 : https://docs.azure.cn/zh-cn/api-management/api-management-howto-log-event-hubs#configure-log-to-eventhub-policies

Logger - Create Or Update : https://docs.microsoft.com/zh-cn/rest/api/apimanagement/2020-12-01/logger/create-or-update#apimanagementcreateehlogger

创建 Azure 事件中心:https://docs.azure.cn/zh-cn/event-hubs/event-hubs-create

下载 Service Bus Explorer查看事件中心消息:https://github.com/paolosalvatori/ServiceBusExplorer/releases

相关实践学习
通过日志服务实现云资源OSS的安全审计
本实验介绍如何通过日志服务实现云资源OSS的安全审计。
相关文章
|
5月前
|
API 网络安全 网络架构
【Azure APIM】解答REST API实现"禁用自签名证书的证书链验证"中的backends参数值从那里取值的问题?
本文介绍APIM服务调用后端API时因自签名证书导致500错误的解决方案。通过REST API禁用证书链验证,关键在于获取正确的backendId(即APIM中配置的Backend名称),并调用PATCH接口设置validateCertificateChain为false,从而解决SSL/TLS信任问题。
218 7
|
9月前
|
XML 安全 API
【Azure APIM】API Management的Policy是否支持 SAML assertion?
本文探讨了API Management是否支持通过策略(如validate-jwt)验证SAML assertion的问题。结论是API Management目前不支持SAML assertion验证,因其为XML-based token,而validate-jwt仅适用于JWT tokens。文章进一步介绍了SAML(安全断言标记语言)的基本原理、Assertion的组成及用途,包括单点登录(SSO)、跨组织身份验证、云服务集成和安全性增强等方面,帮助读者深入了解SAML的工作机制及其应用场景。
134 24
|
6月前
|
API 网络架构 容器
【Azure Container App】查看当前 Container App Environment 中的 CPU 使用情况的API
在扩展 Azure Container Apps 副本时,因 Container App Environment 的 CPU 核心数已达上限(500 cores),导致扩展失败。本文介绍如何使用 `az rest` 命令调用 Azure China Cloud 管理 API,查询当前环境的 CPU 使用情况,并提供具体操作步骤及示例。
213 17
|
6月前
|
安全 API 数据安全/隐私保护
【Azure 环境】Microsoft Graph API实现对Entra ID中应用生成密码的时间天数
本文介绍如何通过 Azure 的 App Management Policy 限制用户在创建 AAD 应用程序的 Client Secret 时设置最长 90 天的有效期。通过 Microsoft Graph API 配置 defaultAppManagementPolicy,可有效控制密码凭据的生命周期,增强安全管理。
174 4
|
11月前
|
JSON API 数据格式
【Azure APIM】如何把APIM中处理的请求的所有请求头保存在日志中?
Azure API Management 默认诊断日志不记录请求的 Header 和 Body 信息。为实现记录,可通过配置 Trace 策略解决。例如,使用 `context.Request.Headers` 和 `context.Request.Body` 获取相关信息,并以 JSON 或字符串格式保存。示例代码展示了如何将 Headers 转换为 JSON 或逗号分隔字符串形式记录。相关参考资料包括 Set Body Policy 和 Trace Policy 官方文档,帮助进一步了解与扩展功能。
263 36
|
11月前
|
存储 Windows
【Azure Cloud Service】微软云服务上的日志收集方法
本文介绍了在使用微软云服务(Cloud Service Extended Support)时,如何收集日志以分析未记录在应用日志中的服务异常。由于云服务基于传统虚拟机模式,需通过远程桌面登录实例,查看IIS、Windows Event及云服务组件日志(如WindowsAzureGuestAgent)。此外,可使用CollectGuestLogs.exe工具打包日志,或通过“File Server Resource Manager”检查日志存储配额是否不足。附参考文档链接供深入学习。
345 29
|
11月前
|
存储 监控 API
【Azure App Service】分享使用Python Code获取App Service的服务器日志记录管理配置信息
本文介绍了如何通过Python代码获取App Service中“Web服务器日志记录”的配置状态。借助`azure-mgmt-web` SDK,可通过初始化`WebSiteManagementClient`对象、调用`get_configuration`方法来查看`http_logging_enabled`的值,从而判断日志记录是否启用及存储方式(关闭、存储或文件系统)。示例代码详细展示了实现步骤,并附有执行结果与官方文档参考链接,帮助开发者快速定位和解决问题。
316 22
|
12月前
|
API 开发工具 Python
|
12月前
|
SQL 缓存
【YashanDB知识库】YashanDB run.log中有slow log queue is full信息
【YashanDB知识库】YashanDB run.log中有slow log queue is full信息
|
5月前
|
缓存 监控 前端开发
顺企网 API 开发实战:搜索 / 详情接口从 0 到 1 落地(附 Elasticsearch 优化 + 错误速查)
企业API开发常陷参数、缓存、错误处理三大坑?本指南拆解顺企网双接口全流程,涵盖搜索优化、签名验证、限流应对,附可复用代码与错误速查表,助你2小时高效搞定开发,提升响应速度与稳定性。