Search code examples
c#.netazure-application-insightsopen-telemetryobservability

How can I configure Azure.Monitor.OpenTelemetry.AspNetCore to add custom properties to any type of telemetry, not just request traces?


I'm using a OTEL tracer processor (CorrelationIdActivityEnrichingProcessor) to add a custom properties to traces emitted to Application Insights.

However, while it successfully add custom properties to request telemetry, nothing is added to trace telemetry:

enter image description here

How can I configure Azure.Monitor.OpenTelemetry.AspNetCore to add custom properties to any type of telemetry, not just request traces?

Code:

        // Add correlation ID to Application Insights telemetry as a custom property
        builder.Services.ConfigureOpenTelemetryTracerProvider((sp, tracerBuilder) => tracerBuilder.AddProcessor(
            new CorrelationIdActivityEnrichingProcessor(
                sp.GetRequiredService<IHttpContextAccessor>(),
                sp.GetRequiredService<ILogger<CorrelationIdActivityEnrichingProcessor>>()
            )
        ));

        builder.Services.AddOpenTelemetry()
        .UseAzureMonitor(options =>
        {
            options.EnableLiveMetrics = true;
        }).ConfigureResource(resourceBuilder =>
        {
            resourceBuilder.AddAttributes([
                new KeyValuePair<string, object>("service.name", "MyApp")
            ]);
        });


public class CorrelationIdActivityEnrichingProcessor(IHttpContextAccessor httpContextAccessor, ILogger<CorrelationIdActivityEnrichingProcessor> logger) : BaseProcessor<Activity>
{
    public override void OnStart(Activity activity)
    {
        var httpContext = httpContextAccessor.HttpContext;
        var correlationId = httpContext?.Request.Headers["correlation-id"].FirstOrDefault();
        if (correlationId != null)
        {
            // logger.LogDebug("Enriching activity with correlation ID: {CorrelationId}", correlationId);
            activity.SetTag("CorrelationId", correlationId);
        }
    }
}

Solution

  • CorrelationIdActivityEnrichingProcessor is an ActivityProcessor and only applies to Activity, which is what becomes RequestTelemetry, DependencyTelemetry. TraceTelemetry is coming from ILogger logs, so you need to write a similar LogRecordProcessor to achieve that.

    Or it maybe easier to put the CorrelationId into ILogger Scopes:

    logger.BeginScope(new List<KeyValuePair<string, object>>
            {
                new KeyValuePair<string, object>("CorrelationId", correlationId),
            }
    

    (Remember to turn on Scopes via https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry/Logs/ILogger/OpenTelemetryLoggerOptions.cs#L36)