Search code examples
c#asp.net-coredependency-injectionazure-application-insightsmasstransit

Application Insights telemetry: annotate telemetry event during masstransit message handling based on message contents


I need to track quota-limited outgoing requests, and the quotas are determined by which account the request is made against. The account information comes from a message and is available at scoped lifetime through MassTransit. The application is configured using Microsoft DI and Autofac.

The documentation on how to do this is scarce. Here's a list of things I've tried:

1 - Manual

I tried registering a scoped (or even transient) ITelemetryInitializer and a scoped tracker (just a box to put data in) where the telemetry initializer then adds properties based on the contents of the tracker.

It seemed the tracker didn't function correctly scoped for unknown reasons, and literally every example use of telemetry initializers have them registered as stateless singletons (a prudent design choice.)

2 - Telemetry Client

I created a custom subclass of OperationTelemetry and attempted to use StartOperation with several properties set. I also tried ReqeustTelemetry. I am uncertain why this did not work, and I got an error message about stopping operations from different threads.

It is not clear from documentation what this actually does. I think it doesn't do what I want.

3 - Possible future work

I am currently looking into creating an ITelemetryProcessorFactory since allegedly this should allow the creation of ITelemetryProcessors that take e.g. scoped services. There is not a lot of documentation.


What am I doing wrong? Why does this simple task seem borderline impossible?


Solution

  • Open Telemetry is handled by System.Diagnostics.DiagnosticSource, so if you want to actually add tags/baggage to the telemetry entries, you could use:

    Activity.Current?.AddTag("key", "value");
    

    Those tags will be reported by whatever underlying OTEL collector is being used.

    If you're using a pre-v8 version of MassTransit, I have no idea if this will work properly considering the no longer supported packages used in that version.