---
title: "Event Hub Policy for Azure API Management: Scalable Logging with Nodinite"
description: Learn how to use the Event Hub Policy for Azure API Management with Nodinite. This guide covers setup, logger configuration, policy examples, and unique benefits for secure, scalable, and actionable logging.
---

# Event Hub Policy

>[!IMPORTANT]
>**Azure Trusted Service Connectivity Retirement (March 2026)** - Microsoft is retiring the Trusted Services feature, which affects logging from APIM to Azure Event Hubs when network restrictions are enabled. Read the [Microsoft announcement](https://learn.microsoft.com/en-us/azure/api-management/breaking-changes/trusted-service-connectivity-retirement-march-2026)<sup>:fa-arrow-up-right-from-square:</sup> and review the [alternative solutions][Network Restrictions & Alternative Solutions] below.

Use scalable, policy-based logging for Azure API Management with :Nodinite:. This guide helps you set up Event Hub logging, configure loggers, and implement policies so you can securely and efficiently track all requests and responses.

✅ Log requests and responses with full payload and headers  
✅ Integrate with Azure Event Hub for scalable, asynchronous logging  
✅ Monitor and manage loggers directly from :Nodinite:  
✅ Use policy-based logging for flexibility and security  
✅ Prevent data loss with robust pickup and monitoring agents  

>[!WARNING]
>The Event Hub logging option enforces a **200 KB** [limit](https://learn.microsoft.com/en-us/azure/api-management/log-to-eventhub-policy#usage-notes)<sup>:fa-arrow-up-right-from-square:</sup>. If you log messages larger than this, the event will not be logged. For large messages, use the [Blob Storage Policy][].

<div class="mermaid">
graph LR
    subgraph "Payload < 200KB"
        A[Azure API Management</br>with Policy 2]
        A --> | 1. Log Event, </br>payload < 200KB | B(Azure Event Hub)  
    end
    subgraph "Nodinite"
        B --> C{Pickup Service}
        C --> F[Log API]
    end
</div>

*Diagram: Event Hub policy-based logging from Azure API Management to Nodinite.*

## Event Hub Overview

You create a :Nodinite: [Log Event][] and send it to Azure Event Hub as intermediate storage. The :Nodinite: [Pickup Log Events Service Logging Agent][] transfers the data to your :Nodinite: instance for use in self-service [Log Views][].

To enable :Nodinite: logging from your APIs in Azure API Management:

* Configure one or more [Event Hub Loggers](#event-hub-logger)  
* Configure the policy within your API  
* Install and configure the :Nodinite: [Pickup Log Events Service Logging Agent][]  
  * Configure it to fetch the :Nodinite: [JSON Log Event][] from the target Event Hub. Provide the **connection string** (create or reuse from 'Shared access policies' in the Azure portal).  

When you activate the policy, **Azure API Management** creates a :Nodinite:-specific [JSON Log Event][] and posts it to the named **Event Hub**. The :Nodinite: [Pickup Log Events Service Logging Agent][] [asynchronously][Asynchronous Logging] moves the [JSON Log Event][] to :Nodinite:.

### Event Hub Logger

To log using Azure Event Hub, create a named **Event Hub Logger**. Reference this logger by name in your policy. You cannot rename a logger—delete and recreate it if needed. Create it using :Nodinite: or tools like Insomnia.

>[!IMPORTANT]
>Add one or more named [Event Hub loggers](https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs)<sup>:fa-arrow-up-right-from-square:</sup> to create the Event Hub Logger used by the Policy. This enables logging to Nodinite using Azure Event Hub as intermediate storage.

>[!TIP]
>Use the :Nodinite: [Azure Monitoring Agent][Azure Agent] to manage and monitor your **Event Hub Loggers**.

* :fa-monitor-waveform: [Monitoring][Azure Agent - Monitoring Logger]  
* :fa-wrench: [Managing][Azure Agent - Managing API Logger]  
  * :fa-circle-info: [Details][Azure Agent - Managing API Logger - Details]  
  * :fa-edit: [Edit][Azure Agent - Managing API Logger - Edit]  
  * :fa-trash-can: [Delete][Azure Agent - Managing API Logger - Delete]  

* [Learn how to call the Azure Rest API using Postman](https://learn.microsoft.com/en-us/rest/api/azure/#how-to-call-azure-rest-apis-with-postman)<sup>:fa-arrow-up-right-from-square:</sup>

>[!IMPORTANT]
>If you use **Postman**, review [Security Risks of Postman](https://www.leeholmes.com/security-risks-of-postman/)<sup>:fa-arrow-up-right-from-square:</sup>.

* Use the ApplicationId/ClientID you created by following the [Azure Application Access][AzureApplicationsAccess] guide  
* [Download Azure REST API Template for Postman](https://app.getpostman.com/run-collection/41b9fa3b957c297f283d#?env%5BAzure%20REST%5D=W3siZW5hYmxlZCI6dHJ1ZSwia2V5IjoidGVuYW50SWQiLCJ2YWx1ZSI6IiIsInR5cGUiOiJ0ZXh0In0seyJlbmFibGVkIjp0cnVlLCJrZXkiOiJjbGllbnRJZCIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifSx7ImVuYWJsZWQiOnRydWUsImtleSI6ImNsaWVudFNlY3JldCIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifSx7ImVuYWJsZWQiOnRydWUsImtleSI6InJlc291cmNlIiwidmFsdWUiOiJodHRwczovL21hbmFnZW1lbnQuYXp1cmUuY29tLyIsInR5cGUiOiJ0ZXh0In0seyJlbmFibGVkIjp0cnVlLCJrZXkiOiJzdWJzY3JpcHRpb25JZCIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifV0=)<sup>:fa-arrow-up-right-from-square:</sup>

You can also create the **Event Hub Logger** by performing a **PUT** method with a **Body**; a template is provided below:

|Method|URL|  
|:---:|---|  
|PUT|`https://management.azure.com/subscriptions/{{subscriptionId}}/resourceGroups/{{resourceGroup}}/providers/Microsoft.ApiManagement/service/{{APIMGMTServiceName}}/loggers/{{loggerName}}?api-version=2024-05-01`|  
|DELETE|`https://management.azure.com/subscriptions/{{subscriptionId}}/resourceGroups/{{resourceGroup}}/providers/Microsoft.ApiManagement/service/{{APIMGMTServiceName}}/loggers/{{loggerName}}?api-version=2024-05-01`|  

* {{subscriptionId}} is the Subscription ID where your API Management Service is located.  
* {{resourceGroup}} is the Resource Group where your API Management Service is located.
* {{APIMGMTServiceName}} is the name of your API Management Service.
* {{loggerName}} is the name you assign to this Event Hub Logger.

The `{loggerName}` uniquely identifies this logger in your API Management Service (`{{APIMGMTServiceName}}`). Use a unique name per Event Hub and environment (Prod, QA, Test, ...).

>[!IMPORTANT]
>Once you reference a Logger in any APIM Policy, you cannot remove it. To change the name, remove all references, drop the old one, and recreate it with the new name.

```json
{
  "properties": {
    "loggerType": "azureEventHub",
    "description": "{description}",
    "resourceId": "{resourceId}",
    "credentials": {
      "name": "{`eventHubEntityName`}",
      "connectionString": "Endpoint=sb://{namespace}.servicebus.windows.net/;SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={entityPath}"
    }
  }
}
```

*Use this **Body** as a template and modify it for your needs.*

|Field|Variable|Value|Description|  
|---|---|---|---|  
|:fa-code-branch: `loggerType`|-|`azureEventHub`|Hard coded value. DO NOT CHANGE!|  
|:fa-align-left: `description`|`{description}`|`Doing good`|Add a user-friendly description for this Event Hub Logger|  
|:fa-fingerprint: `resourceId`|`&#123;resourceId&#125;`|<pre style="max-width: 500px"><code>/subscriptions/&#123;SubscriptionId&#125;/resourceGroups/&#123;ResourceGroupName&#125;/providers/Microsoft.EventHub/namespaces/&#123;EventHubNamespaceName&#125;/eventhubs/&#123;eventhubName&#125;</code></pre>|**NOTE:** The target Event Hub Entity may be in another subscription/resource group. Enter values accordingly.|  
|:fa-tag: `name`|`{eventHubEntityName}`|`eventHubEntityName`|**OPTIONAL:** Name of the Event Hub Entity if not provided in the connection string|  
|:fa-plug: `connectionString`|`{namespace}`||The **namespace** with the **target** Event Hub|  
|:fa-plug: `connectionString`|`{sharedAccessKeyName}`||Name of the shared access key|  
|:fa-plug: `connectionString`|`{sharedAccessKey}`||The shared access key for the provided key name|  
|:fa-plug: `connectionString`|`{entityPath}`||Name of the **target event hub entity** for :Nodinite: [JSON Log Event][]. If you provide `{entityPath}`, you do not need to specify `{eventHubEntityName}`|  

>[!TIP]
>Use a SAS key with **Manage** permission to create the Event Hub Logger. The **Send** permission is not enough. We recommend a dedicated SAS key for each Event Hub Logger for easy revocation and best security.

### API Policy Configuration

Decide what to log (Request and/or Response) and add the configuration to your policy in the inbound, outbound, or both sections.

||Direction|Type|  
|:---:|---|---|  
|:fa-sign-in:|Inbound|Request|  
|:fa-sign-out:|Outbound|Response|  

The template below logs:

* Mandatory properties for a :Nodinite: [Log Event][] (modify as needed for your business)
* HTTP Headers as context properties  
  >[!INFO]
  >Some properties are excluded in the sample code
* Body

Replace '`{loggerName}`' in both the API management logger and the code snippets below for the **Policy configuration**.

The example below creates a basic :Nodinite: [JSON Log Event][] with common, mandatory, and optional properties.

* Context is optional
* Body is optional (note the 200 KB limit on the JSON using the Event Hub Logger; consider [Blob Storage Policy][Blob Storage Policy][] for larger messages).

```xml
<log-to-eventhub logger-id='{loggerName}'>
    @{
    var body =  context.Request.Body.As<string>(preserveContent: true);

    var bodyToLog = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(body));

    var headers = context.Request.Headers
                .Where(h => h.Key != "Authorization" && h.Key != "Ocp-Apim-Subscription-Key");

    Dictionary<string, string> contextProperties = new Dictionary<string, string>();
    foreach (var h in headers) {
        contextProperties.Add(string.Format("Header#{0}", h.Key), String.Join(", ", h.Value));
    }
    
    var requestLogMessage = new {
        LogAgentValueId = 15,
        EndPointName = context.Deployment.ServiceName + "/" + context.Api.Name + "/" + context.Operation.Name,
        EndPointUri = context.Deployment.ServiceName + "/" + context.Api.Name + "/" + context.Operation.Name,
        EndPointDirection = 10,
        EndPointTypeId = 71,
        OriginalMessageTypeName = "Nodinite.Schemas/Nodinite.Demo/5.0#Orders",
        LogDateTime = DateTime.UtcNow,
        Context = contextProperties,
        Body = bodyToLog
    };

    return JsonConvert.SerializeObject(requestLogMessage);
    }
</log-to-eventhub>
```

### Example Azure Event Hub Policy

This complete policy logs both **inbound** (Request) and **outbound** (Response) information.

>In this example, you add a **clientTrackingId** (guid) if not provided in the **x-ms-client-tracking-id** HTTP header, plus other optional properties for a :Nodinite: [Log Event][].

```json
x-ms-client-tracking-id
```

```xml
<policies>
    <inbound>
        <!-- creating a tracking/correlation id -->
        <set-variable name="clientTrackingId" value="@{ 
            return Guid.NewGuid().ToString();
        }" />
        <!-- if x-ms-client-tracking-id exists use it, if not, use clientTrackingId -->
        <set-header name="x-ms-client-tracking-id" exists-action="skip">
            <value>@(context.Variables.GetValueOrDefault<string>("clientTrackingId"))</value>
        </set-header>
        <!-- Put on logger -->
        <log-to-eventhub logger-id="{loggerName}">
            @{
                var body =  context.Request.Body.As<string>(preserveContent: true); // in case we need it later...

                var bodyToLog = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(body));

                var headers = context.Request.Headers
                            .Where(h => h.Key != "Authorization" && h.Key != "Ocp-Apim-Subscription-Key");

                var correlationId = headers.Any(h=>h.Key == "x-ms-client-tracking-id") ? headers.First(h => h.Key == "x-ms-client-tracking-id").Value[0] : context.Variables.GetValueOrDefault<string>("clientTrackingId"); 

                Dictionary<string, string> contextProperties = new Dictionary<string, string>();
                contextProperties.Add("Correlation Id", correlationId);
            
                foreach (var h in headers) {
                    contextProperties.Add(string.Format("Header#{0}", h.Key), String.Join(", ", h.Value));
                }
                
                var requestLogMessage = new {
                    LogAgentValueId = 15,
                    EndPointName = context.Deployment.ServiceName + "/" + context.Api.Name + "/" + context.Operation.Name,
                    EndPointUri = context.Deployment.ServiceName + "/" + context.Api.Name + "/" + context.Operation.Name,
                    EndPointDirection = 10,
                    EndPointTypeId = 71,
                    EventDirection=21,
                    OriginalMessageTypeName = "Nodinite.Schemas/Nodinite.Demo/5.0#Orders",
                    LogDateTime = DateTime.UtcNow,
                    LogStatus = 0,
                    ApplicationInterchangeId = correlationId,
                    Context = contextProperties,
                    LogText = "Hello World from Nodinite API mgmt logging policy",
                    Body = bodyToLog
                };

                return JsonConvert.SerializeObject(requestLogMessage);
            }
        </log-to-eventhub>
    </inbound>
    <backend>
        <forward-request />
    </backend>
    <outbound>
        <!-- if x-ms-client-tracking-id exists use it, if not, use clientTrackingId -->
        <set-header name="x-ms-client-tracking-id" exists-action="skip">
            <value>@(context.Variables.GetValueOrDefault<string>("Correlation Id"))</value>
        </set-header>
        <log-to-eventhub logger-id="{loggerName}">
            @{
                var body =  context.Response.Body.As<string>(preserveContent: true); // in case we need it later...

                var bodyToLog = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(body));

                var headers = context.Response.Headers
                            .Where(h => h.Key != "Authorization" && h.Key != "Ocp-Apim-Subscription-Key");
                
                var correlationId = headers.Any(h=>h.Key == "x-ms-client-tracking-id") ? headers.First(h => h.Key == "x-ms-client-tracking-id").Value[0] : context.Variables.GetValueOrDefault<string>("clientTrackingId"); 

                Dictionary<string, string> contextProperties = new Dictionary<string, string>();
                contextProperties.Add("Correlation Id", correlationId);
                foreach (var h in headers) {
                    contextProperties.Add(string.Format("Header#{0}", h.Key), String.Join(", ", h.Value));
                }
                string logText = "";

                if (context.Response.StatusCode > 300)
                {
                    logText = "Guru meditation";
                }
                
                var requestLogMessage = new {
                    LogAgentValueId = 15,
                    EndPointName = context.Deployment.ServiceName + "/" + context.Api.Name + "/" + context.Operation.Name,
                    EndPointUri = context.Deployment.ServiceName + "/" + context.Api.Name + "/" + context.Operation.Name,
                    EndPointDirection = 10,
                    EndPointTypeId = 71,
                    EventDirection=25,
                    OriginalMessageTypeName = "Nodinite.Schemas/Nodinite.Demo/5.0#OrderResponses",
                    LogDateTime = DateTime.UtcNow,
                    ApplicationInterchangeId = correlationId,
                    Context = contextProperties,
                    Body = bodyToLog,
                    LogStatus = context.Response.StatusCode,
                    LogText = logText
                };
                return JsonConvert.SerializeObject(requestLogMessage);
            }
        </log-to-eventhub>
    </outbound>
    <on-error />
</policies>
```

___

## Redacting Sensitive Data

>[!IMPORTANT]
>**Protect sensitive information in your logs** - By default, the policy examples exclude `Authorization` and `Ocp-Apim-Subscription-Key` headers to prevent logging credentials. Review your headers and request/response bodies to ensure no PII (Personally Identifiable Information), secrets, passwords, or API keys are logged.

### Best Practices

* :fa-filter: **Filter headers**: Exclude headers containing sensitive data (authentication tokens, API keys, secrets)
* :fa-eraser: **Redact body content**: Hash or remove PII fields from request/response bodies before logging
* :fa-list-check: **Use allowlists**: Log only known-safe headers instead of denylisting sensitive ones
* :fa-clipboard-check: **Audit regularly**: Review logged data to ensure compliance with data protection regulations

#### Example Header Filtering

```csharp
var headers = context.Request.Headers
    .Where(h => h.Key != "Authorization" && h.Key != "Ocp-Apim-Subscription-Key");
```

>[!TIP]
>APIM adds diagnostic headers such as `Ocp-Apim-Trace-AuthorizationExpired` to responses. These are captured by `context.Response.Headers` in the outbound section and will appear as context properties in :Nodinite: logs. See [APIM Troubleshooting][] if you want to understand or suppress them.

For advanced redaction techniques, custom body filtering, and security hardening options, see [Network Restrictions & Alternative Solutions - Redact Sensitive Data][Network Restrictions & Alternative Solutions].

___

## Troubleshooting

Contact our [Support][] if you need help implementing [Logging][].

## Network Restrictions & Troubleshooting

>[!IMPORTANT]
>**Are you experiencing issues with network-restricted Event Hubs?** Due to Azure's Trusted Services retirement (March 2026), logging from APIM to Event Hubs with firewall restrictions requires alternative solutions. See our comprehensive guide: [Network Restrictions & Alternative Solutions][].

For the ports and hostnames to allow on each hop, see the [firewall settings for Azure API Management logging][APIM firewall].

**Quick summary of available options:**

1. **Private Endpoint with VNet Integration** ✅ Recommended - Best for production (requires Developer/Premium/Standard v2 tier)
2. **Direct [Log API Policy][]** - Works on all APIM tiers including Consumption
3. **Switch to Blob Storage Policy** - Better for large messages (>200 KB)
4. **Azure Function/Logic App Intermediary** - Flexible middle-ground solution
5. **Upgrade to Developer Tier** - Cost-effective option for dev/test (~$50/month)

>[!NOTE]
>Event Hub has a **200 KB message size limit**. For larger payloads, consider switching to [Blob Storage Policy][] combined with one of the alternative solutions.

👉 [Read the full troubleshooting guide][Network Restrictions & Alternative Solutions] for detailed implementation steps, pricing information, and recommendation matrix.

___

## :fa-hand-point-right: Next Steps

:fa-magnifying-glass-plus: [Search Fields][]  
:fa-search: [Log Views][]  

## :fa-link-horizontal: Related Topics

* [Blob Storage Policy][]  
* [Log API Policy][]  
* :fa-coins: [Reduce Azure API Management Logging Costs][]  

:fa-user-secret: [Azure Application Access][AzureApplicationsAccess]  
:fa-file-code: [JSON Log Event][]  
:fa-wrench: [Managing][Azure Agent - Managing API Logger]  
:fa-monitor-waveform: [Monitoring][Azure Agent - Monitoring Logger]  
:fa-clock: [Non Events Agent][]  
:fa-truck-pickup: [Pickup Log Events Service Logging Agent][]  

Interested in logging from other Azure Related Services?

* [Logging from Azure Logic Apps][LogicAppsAgent]  
* [Logging from Azure Functions][Serilog]  

[APIM firewall]:{ndr}/Logging%20and%20Monitoring/Azure%20API%20Management/Overview.md#fa-shield-check-what-firewall-settings-are-required-for-azure-api-management-logging
[APIM Troubleshooting]:{ndr}/Logging%20and%20Monitoring/Azure%20API%20Management/Troubleshooting/Overview.md
[Asynchronous Logging]:{ndr}/Core%20Services/Log%20API/Features/Asynchronous%20Logging.md
[Azure Agent]:{ndr}/Logging%20and%20Monitoring/Azure/Overview.md
[Azure Agent - Managing API Logger]:{ndr}/Logging%20and%20Monitoring/Azure/Features/API%20Management/Event%20Hub%20Logger/Managing%20Logger.md
[Azure Agent - Managing API Logger - Delete]:{ndr}/Logging%20and%20Monitoring/Azure/Features/API%20Management/Event%20Hub%20Logger/Managing%20Logger.md#fa-trash-can-delete
[Azure Agent - Managing API Logger - Details]:{ndr}/Logging%20and%20Monitoring/Azure/Features/API%20Management/Event%20Hub%20Logger/Managing%20Logger.md#fa-circle-info-details
[Azure Agent - Managing API Logger - Edit]:{ndr}/Logging%20and%20Monitoring/Azure/Features/API%20Management/Event%20Hub%20Logger/Managing%20Logger.md#fa-edit-edit
[Azure Agent - Monitoring Logger]:{ndr}/Logging%20and%20Monitoring/Azure/Features/API%20Management/Event%20Hub%20Logger/Monitoring%20Logger.md
[AzureApplicationsAccess]:{ndr}/Install%20and%20Update/Troubleshooting/Azure/Azure%20Application%20Access.md
[Blob Storage Policy]:{ndr}/Logging%20and%20Monitoring/Azure%20API%20Management/Policy/Blob%20Storage.md
[JSON Log Event]:{ndr}/Core%20Services/Log%20Event/Features/JSON%20Log%20Event.md
[Log API Policy]:{ndr}/Logging%20and%20Monitoring/Azure%20API%20Management/Policy/Log%20API.md
[Log Event]:{ndr}/Core%20Services/Log%20Event/Overview.md
[Log Views]:{ndr}/Administration/1.%20Log%20Management/1.%20Log%20Views/Features/What%20is%20a%20Log%20View.md
[Logging]:nodiniteDoc:/Logging
[LogicAppsAgent]:{ndr}/Logging%20and%20Monitoring/Azure%20Logic%20Apps/Overview.md
[Network Restrictions & Alternative Solutions]:{ndr}/Logging%20and%20Monitoring/Azure%20API%20Management/Policy/Network%20Restrictions.md
[Non Events Agent]:{ndr}/Logging%20and%20Monitoring/Non-Events/Overview.md
[Pickup Log Events Service Logging Agent]:{ndr}/Logging%20and%20Monitoring/Pickup%20LogEvents%20Service/Overview.md
[Reduce Azure API Management Logging Costs]:{ndr}/Logging%20and%20Monitoring/Azure%20API%20Management/Troubleshooting/Reduce%20Azure%20API%20Management%20Logging%20Costs.md
[Search Fields]:{ndr}/Administration/1.%20Log%20Management/2.%20Search%20Fields/Features/What%20is%20a%20Search%20Field.md
[Serilog]:{ndr}/Logging%20and%20Monitoring/Serilog/Overview.md
[Support]:https://support.nodinite.com