APIM中如何生成带records数组的JSON结构发送至EventHub
解决APIM log-to-eventhub策略生成records数组结构JSON的问题
修改后的完整策略代码
<log-to-eventhub logger-id="testjayeventhub">@{ // 创建原有的日志条目对象 var logEntry = new JObject( new JProperty("EventTime", DateTime.UtcNow.ToString()), new JProperty("ServiceName", context.Deployment.ServiceName), new JProperty("RequestId", context.RequestId), new JProperty("RequestIp", context.Request.IpAddress), new JProperty("OperationName", context.Operation.Name) ); // 创建records数组并添加日志条目 var recordsArray = new JArray(); recordsArray.Add(logEntry); // 构建外层对象,包含records属性 var outerObject = new JObject( new JProperty("records", recordsArray) ); return outerObject.ToString(); }</log-to-eventhub>
关键实现逻辑
你已经完成了日志对象和数组的创建,只需要多一步:把数组包装到一个带records字段的外层JObject里。具体就是:
- 保留你写好的
logEntry(单条日志JObject)和recordsArray(存储日志的JArray) - 新建外层JObject,添加名为
records的属性,值就是上面的数组 - 最终返回外层JObject的字符串形式,就能生成目标结构
生成的目标结构验证
修改后发送到EventHub的JSON将符合预期:
{ "records": [ { "EventTime": "...", "ServiceName": "yyyy", "RequestId": "yyyy", "RequestIp": "yyy", "OperationName": "xxx" } ] }
内容的提问来源于stack exchange,提问作者Jayendran
相关产品推荐
相关产品推荐

