How to log APIM events to Event Hub?

ericOnline 21 Reputation points
2023-07-26T19:31:44.79+00:00

Hello,

I've been working a couple days setting up an APIM layer in front of Azure Open AI. This is for logging, throttling, etc.

The APIM resource is setup and accepting requests using APIM Subscription API keys. I've successfully setup an Event Grid logger and connected it to the APIM resource.

Now I'm trying to add a policy to log all requests and responses to the Event Hub. I can't quite understand the syntax for APIM Policies.

I'm trying to use the official "Interact with JSON bodies" snippet, but this produces an error when I just plug it in. I've also referenced the official "Log events to Event Hub" doc. Both references show different syntax, so I'm a bit stuck.

Error:

One or more fields contain incorrect values:

  • The 'JObject' start tag on line 6 position 45 does not match the end tag of 'log-to-eventhub'. Line 7, position 11.

Policy:

<policies>
    <inbound>
        <base />
        <set-backend-service backend-id="my-apim-backend" />
        <log-to-eventhub logger-id="my-eventhub-logger" partition-id="1">
            (string)context.Request.Body.As<JObject>(preserveContent:true)
        </log-to-eventhub>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Does anyone see what I'm doing wrong? How do I get the request to log to Event Hub logger?

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,960 questions
{count} votes

Accepted answer
  1. Pramod Valavala 20,611 Reputation points Microsoft Employee
    2023-07-26T20:29:39+00:00

    @ericOnline The problem is because you can't cast a JObject to a string directly, instead you need to serialize it. Better yet, since you are not modifying the body, you might as well just get it as a string in the first place.

    Try a policy like this one

    <log-to-eventhub logger-id="my-apim-logger" partition-id="1">
    	@(context.Request.Body.As<string>(preserveContent: true))
    </log-to-eventhub>
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful