Get traceparent generated by APIM and return from response header

He Gao 6 Reputation points
2021-11-15T08:21:45.46+00:00

By correlate requests in Azure APIM and Application Insight with W3C distributed tracing Azure, if the client dose not send the traceparent header, seems APIM would checks the incoming request and if no traceparent, the APIM would generate and set from the request goes to backend.

In this case, we would like to return the traceparent information from the frontend response header so the consumer who inoke the API would get it, they could report API issue with this traceparent id so we can better trace/diagnose it with service log.

The question is how to get the APIM generated traceparent from inbound/outbound policy, please suggest a approach, thanks !

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,457 questions
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Pramod Valavala 20,656 Reputation points Microsoft Employee Moderator
    2021-12-07T11:57:35.397+00:00

    @He Gao When trying with a simple API with APIM injecting the trace parent and the backend responding with the trace parent, the final response should already have it.

    I assume the backend doesn't include it in the response and/or you build the response object in which case you could still fetch it using context.Request.Headers.GetValueOrDefault("traceparent", "") policy expression in the outbound scope.

    I tried this out with the Echo API with the following policy document and it worked as expected

       <policies>  
           <inbound>  
               <base />  
           </inbound>  
           <backend>  
               <base />  
           </backend>  
           <outbound>  
               <base />  
               <set-header name="X-TRACE-PARENT-ID" exists-action="override">  
                   <value>@(context.Request.Headers.GetValueOrDefault("traceparent", ""))</value>  
               </set-header>  
           </outbound>  
           <on-error>  
               <base />  
           </on-error>  
       </policies>  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.