Activity.Current is null on HttpRequestOut.Stop

1.5k views Asked by At

I'm using Application Insights for Console App (.NET Core 2.1).

I need to gather more information about dependencies(requests/responses) than ApplicationInsights.DependencyCollector does.

So I've tried the approach described in this blog. And it works for requests.
But it does not work for responses. Because in the code above Activity.Current is null:

[DiagnosticName("System.Net.Http.HttpRequestOut.Stop")]
public virtual void OnHttpRequestOutStop(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpResponseMessage response, TaskStatus requestTaskStatus)
{
    Console.WriteLine(Activity.Current);
}

While in the similar code for HttpRequestOut.Start it has proper value:

[DiagnosticName("System.Net.Http.HttpRequestOut.Start")]
public virtual void OnHttpRequestOutStart(System.Net.Http.HttpRequestMessage request)
{
    Console.WriteLine(Activity.Current);
}

Why in System.Net.Http.HttpRequestOut.Stop event the Activity.Current is null?
How can I access the same activity in Start and Stop events?

UPDATE:
I've found some info about the issue here.

1

There are 1 answers

1
qwermike On BEST ANSWER

This comment really helped.

The most complicated scenario is when you want to access response and enrich telemetry based on it. you can still use diagnostic source Stop event, however, this becomes hacky because AppInsights listens to the same even and your listener needs to receive the Stop event before AppInsights.

So I just initialized my 'enrichment' observer class before the telemetry client. And Activity.Current is no longer null in OnHttpRequestOutStop.