Hangfire logging to Application Insights from job enqueued from controller

Viewed 137

When I enqueue a job from a controller with Hangfire, telemetry is not correlated in Application Insights:

public IActionResult Foo()
{
    _backgroundJobClient.Enqueue<IFooService>(x => x.StartJob());
    
    return StatusCode((int) HttpStatusCode.Accepted);
}

For comparison, logs from this controller will have the same operationId:

public IActionResult Hello()
{
    _logger.LogInformation("Hello.");
    _logger.LogInformation("Hello 2.");
    return Ok();
}

Also, logs from a hosted service (non-HTTP workloads) will be correlated when manually creating an operation:

public class MyHostedService : IHostedService, IDisposable
{
    public MyHostedService(ILogger<MyHostedService> logger)
    {
        _logger = logger;
    }
    
    public Task StartAsync(CancellationToken stoppingToken)
    {
        using var operationHolder = _telemetryClient.StartOperation<RequestTelemetry>("MyHostedService");

        _logger.LogInformation("Running.");

        ...
    }
}

How can make logs to Application Insights have the same operationId when a job is enqueued from a controller?

0 Answers
Related