Azure APIM
User logs are Injected in Application Insight
Problem Statement
The current API gateway does not provide user details along with incoming requests. As a result, it is not possible to reliably track which user is accessing specific APIs.
Solution:
We can implement an inbound policy in the API Gateway to capture trace information. These traces will be sent to Application Insights, where they can be later used to track and analyze user activity. We can also store thes logs to database for future references
Intro — Azure API Management (APIM) gateway (short & practical)
Azure API Management (APIM) is a managed gateway that sits in front of your APIs and provides a central place to secure, publish, transform, and observe traffic. With APIM you can:
apply policies (XML fragments) at global, API, or operation level to throttle, rewrite, authenticate, cache, log, or transform requests and responses; Microsoft Learn+1
enrich requests and responses (add headers, inject correlation IDs) so downstream services and telemetry systems can correlate traces; Microsoft Learn+1
This makes APIM an ideal place to add lightweight observability (user identity, correlation id, subscription id, client IP) for every incoming call, even when the backend or client doesn’t supply all the fields you need.
Now let’s dive into required steps to create api gateway, configure it with application insight and add traces.
Step by Step Process:
Create Http API with url detail in Gateway and Add operations
Select the operation inside All Operation and click on inbound processing => Polices (</>)
In Inbound polices, once you click (</>) your can paste code as shown below. Adding this policy will include the email of the user who logged In and forward it to related Application insight of the API .
<inbound>
<base />
<set-header name=”user-email” exists-action=”override”>
<value>@(context.User != null ? context.User.Email : “unknown”)</value>
</set-header>
<trace source=”APIM” severity=”information”>
<message>@($”userEmail:{(context.User != null ? context.User.Email : “unknown”)}”)</message>
</trace>
</inbound>In API Settings tab look for Diagnostics Logs => Application Insights and click on Enable checkbox . In the Destination dropdown select your application insight and save it
Navigate to application insight => Transaction search and look for traces of API request in last 24 hours. In traces you wil find all the details you added in inbound policy
Summary
In this article, we explored how to extend Azure API Management (APIM) Gateway with custom policies to improve user tracking and observability.
By combining APIM policies with Application Insights telemetry, you create a robust monitoring setup that allows you to trace user activity across every API call, troubleshoot issues quickly, and gain better insights into how APIs are being consumed.







