Search code examples
c#azure.net-coreazure-functionsazure-application-insights

Logging With Correlation Id in Azure Function


Can anybody please suggest me how i can achieve adding correlation id for traceability of every http request to below function.

[FunctionName("GetCars")]
public async Task<IActionResult> GetCars([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "api/v1/id/{id}")] HttpRequest req, Guid id)
{
    try
    {
        if (id == Guid.Empty)
        {
            _logger.LogError("Id is Empty");
        }

        var cars= _deviceService.GetCars(id);

        return new OkObjectResult(cars);
    }
    catch (Exception ex)
    {               
        _logger.LogError(ex, "Failed to Fetch Cars");
                
    }
}

Solution

  • So if I am not mistaken, what you want is that in case of an Exception you can return *something* in the body so you can find that occurence in Application Insights? If so, try this:

    var requestTelemetry = req.HttpContext.Features.Get<RequestTelemetry>();
    var operationId = requestTelemetry.Context.Operation.Id;
    

    and send the operationId as part of the result.

    The operationId can be used to track the whole operation, from request till exception, in Application Insights.