Skip to content

DiagnosticsHandler doesn't support W3C trace context correctly with aspnetcore #31862

@gislikonrad

Description

@gislikonrad

I have two aspnetcore applications using the W3C activity id format. When I have one call the other, the tracing context in the logs is missing a link in the chain.

Expected behavior
Trace id is the same in the logs of both services.
Parent id in the logs for the second service matches the span id in the logs of the first service.

Observed behavior
Trace id is the same in the logs of both services.
Parent id in the logs for the second service does not match the span id in the logs of the first service.

This is due to what is happening in the DiagnosticsHandler.

On line 52, the DiagnosticListener (s_diagnosticListener) is queried for whether it's enabled. This is always false for .net core. In this statement, a new activity is started and not logged. The part of the method that we want to run (line 95-99) is never run.

I have currently hacked this to work in my project with the following code

internal static class TraceContextHack 
{
    private static readonly string _diagnosticsHandlerTypeFullName = "System.Net.Http.DiagnosticsHandler";
    private static readonly string _diagnosticListenerFieldName = "s_diagnosticListener";

    public static void Initialize()
    {
        var handlerType = typeof(HttpClient).Assembly.GetType(_diagnosticsHandlerTypeFullName);
        var listenerField = handlerType.GetField(_diagnosticListenerFieldName, BindingFlags.NonPublic | BindingFlags.Static);
        var listener = listenerField.GetValue(null) as DiagnosticListener;

        if (!listener.IsEnabled())
            listener.Subscribe(new NullObserver(), _ => false);
    }
}

class NullObserver : IObserver<KeyValuePair<string, object>>
{
    public void OnCompleted()
    {
    }

    public void OnError(Exception error)
    {
    }

    public void OnNext(KeyValuePair<string, object> value)
    {
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions