【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信任问题。
229 7
|
6月前
|
人工智能 搜索推荐 算法
唯品会 API 开启唯品会店铺精准营销新策略
在竞争激烈的电商市场中,唯品会作为领先的折扣平台,通过API技术助力商家实现精准营销。API为商家提供用户行为、商品与交易数据,支撑用户画像、个性化推荐、动态定价、跨渠道营销与库存预测等策略,提升转化率与用户忠诚度,推动销售增长与营销智能化升级。
267 1
|
5月前
|
SQL 存储 监控
SQL日志优化策略:提升数据库日志记录效率
通过以上方法结合起来运行调整方案, 可以显著地提升SQL环境下面向各种搜索引擎服务平台所需要满足标准条件下之数据库登记作业流程综合表现; 同时还能确保系统稳健运行并满越用户体验预期目标.
330 6
|
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 使用情况,并提供具体操作步骤及示例。
235 17
|
6月前
|
存储 监控 前端开发
淘宝商品详情 API 实战:5 大策略提升店铺转化率(附签名优化代码 + 避坑指南)
本文深入解析淘宝商品详情API的核心字段与实战应用,分享如何通过动态定价、库存预警、差评控制等5大策略提升电商转化率。结合300+店铺实战经验,提供优化代码与避坑指南,助力开发者与运营者实现数据驱动的精细化运营。
|
6月前
|
数据采集 监控 API
亚马逊:对接竞品监控API实时跟踪价格变动,调整定价策略
在电商竞争中,亚马逊通过对接竞品监控API,实现价格实时采集与分析,动态调整定价策略。本文详解其技术实现、商业价值及挑战,展现数据驱动下的智能定价如何提升竞争力与利润。
685 0
|
6月前
|
人工智能 算法 搜索推荐
拼多多:通过用户分组API实施差异化营销策略,提高客单价
拼多多通过用户分组API实现差异化营销,精准提升客单价。基于用户行为数据自动分类,针对不同群体推送专属优惠,如高频用户推高端商品、新用户送礼包、低频用户唤醒激励。结合满减、捆绑销售等策略,有效提高单笔订单金额。该策略提升营销效率,增强用户粘性,助力平台实现数据驱动的可持续增长。
429 0
|
6月前
|
供应链 算法 API
网易严选 API 助力,品质电商商品选品策略升级
在电商竞争激烈背景下,网易严选通过开放商品数据API,提供动态选品解决方案,助力合作伙伴精准决策,实现效率与品质双提升,推动电商战略升级。
165 0
|
存储 API 开发工具
详说Azure的服务运行时API
详说Azure的服务运行时API  【版权声明】原创,作者为chszs,转载需注明。 一、服务运行时API简介   微软的Windows Azure服务总线提供了一整套REST风格的API,其中包括服务运行时API(Service Runtime API)和服务管理API(Service Management API),分别用于运行时操作和管理操作。
929 0
|
存储 API 开发工具
详说Azure的服务运行时API
版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。 https://blog.csdn.net/chszs/article/details/7851794 详说Azure的服务运行时API  【版权声明】原创,作者为chszs,转载需注明。
830 0