Search code examples
asp.netasp.net-core-middlewareopen-telemetryrequest-pipeline

Adding a tag to the ASP.NET Request Activity


I would like to add a tag to the System.Diagnostics.Activity object for each incoming ASP.NET Request, as soon as the request-handling starts. Is there a way I can access the ActivitySource for the Request Pipeline, and add a listener to it?

Currently I'm thinking of using a Pipeline middleware, but there has to be a more lightweight way. Especially one where other developers can't add any other middleware handlers before this one. Any ideas?


Solution

  • Looks like you can add it via DI at startup. The Key thing is the name of the ActivitySource. I couldn't find it in any documentation. I had to trawl through the aspnetcore code, and it looks like registers an empty name ActivitySource for the DiagnosticListener.

    In any case ...

    Add the following to Configure(...):

    var requestActivityListener= new ActivityListener();
    requestActivityListener.ShouldListenTo = activitySource => activitySource.Name == "";
    requestActivityListener.ActivityStarted = activity => LetsShapeThisActivityToOurLiking(activity);
    ActivitySource.AddActivityListener(requestActivityListener);
    

    That should be it.