Freigeben über


Detect backend api response latency using APIM policy

Recently I had a query from a developer asking is there a way to identify response time by backend API by using Azure API management policy expression.
There is no direct policy expression which tracks the response time by backend API. However, we can use few policy expressions in Inbound and outbound to achieve the same.
For example, I used the set-variable policy expression to store current DateTime, one in inbound (i.e. request received time) and another in outbound (i.e. response received time) and then subtracted request received time from response received time to find the difference between the two which will be the time taken by the backend APIs.

Here's how the policy configuration looks like:

 <policies>
 <inbound>
 <set-variable name="Time1" value="@(DateTime.Now)" />
 <base />
 </inbound>
 <backend>
 <base />
 </backend>
 <outbound>
  <set-variable name="Time2" value="@(DateTime.Now-context.Variables.GetValueOrDefault<DateTime>("Time1"))" /> 
 <log-to-eventhub logger-id="neweventlogger">
 @( string.Join(",", DateTime.UtcNow, context.Deployment.ServiceName, context.RequestId, context.Request.IpAddress, context.Operation.Name,context.User.Email,context.Variables.GetValueOrDefault<TimeSpan>("Time2") ) ) 
 </log-to-eventhub>
 <base />
 </outbound>
</policies>            

This policy return string as:
'11/25/2016 12:31:39 PM,kalpitsinghtest.azure-api.net,bc9f3ace-39dd-43ba-a1c0-d65176210ce1,52.187.51.17,Create resource,user@domain.com,00:00:00.4233085'

Let me know how it goes.

Happy Coding!