Search code examples
azure-application-insightsevent-flow

Distinguish applications emitting events to AI using Microsoft.Diagnostics.EventFlow


I have two services running in Azure Service Fabric. Now, i want to capture some events from both and redirect them to the same instance of AI.

My eventFlowConfig.json looks like this:

{
    "inputs": [
        {
            "type": "EventSource",
            "sources": [
                {
                    "providerName": "My-Provider-Name"
                }
            ]
        }
    ],
    "outputs": [
        {
            "type": "ApplicationInsights",
            "instrumentationKey": "AI_INSTRUMENTATION_KEY"
        }
    ],
    "schemaVersion": "2016-08-11"
}

This works just fine. One problem though: in AI I cannot tell if a particular trace item came from service A or service B. So, i need a way to add some custom property to AI items coming from a particular app (service). Like, "Service A" or "Service B". Ideally, i should also be able to add PartiotionId & ReplicaOrInstanceId of that service instance, but that is a bonus without which i can live.

UPDATE:

As @cijothomas suggested, we can use an ITelemetryInitializer. This works because EventFlow uses TelemetryConfiguration.Active. We can do this in the constructor of our service:

TelemetryConfiguration.Active.TelemetryInitializers.Add(new TelemetryInitializer("Service A", context.TraceId));

And here is the definition for the TelemetryInitializer class:

class TelemetryInitializer : ITelemetryInitializer
{
    private readonly string _roleName;
    private readonly string _roleInstance;

    public TelemetryInitializer(string roleName, string roleInstance)
    {
        _roleName = roleName;
        _roleInstance = roleInstance;
    }

    public void Initialize(ITelemetry telemetry)
    {
        telemetry.Context.Cloud.RoleName = _roleName;
        telemetry.Context.Cloud.RoleInstance = _roleInstance;
    }
}

Solution

  • If same ikey is used for multiple apps, they can be distinguished using their cloudRoleInstance. If its not auto-populated, then you can write own telemetry initializer to populate it correctly. https://learn.microsoft.com/en-us/azure/azure-monitor/app/api-filtering-sampling#add-properties-itelemetryinitializer

    item.Context.Cloud.RoleInstance = "service A or B"