microsoft / ApplicationInsights-node.js

Microsoft Application Insights SDK for Node.js
MIT License
324 stars 141 forks source link

Use TelemetryProcessor to overwrite operation name as express route template #702

Closed AlexDenton closed 3 years ago

AlexDenton commented 3 years ago

I think this issue suggests the same idea but it's not clear to me if it's actually possible with available data https://github.com/microsoft/ApplicationInsights-node.js/issues/532

I have an express app and basically want the operations in AI to be grouped by the route template. So instead of having a million operations for each issue:

I want them to all be grouped by the route template so something like /issues/:id. I tried to look through the schema available to telemetry processors here:

telemetryProcessor: (envelope: ContractsModule.Contracts.Envelope, context: { http.RequestOptions, http.ClientRequest, http.ClientResponse, correlationContext }) => boolean;

But I didn't find anything resembling the route template. Nor do I see a way of passing addition data like the route template myself. Is this possible? If so, how?

Thanks!

AlexDenton commented 3 years ago

After sleeping on it I suppose I could just regex it. Still curious if there's a better way?

markwolff commented 3 years ago

@AlexDenton I think this is the approach I would take as well. There is no built-in express integration in this SDK to supply your own route template. As an alternative, you could write your queries on the Portal differently, e.g. | where request.url startswith "foo.com/issues/", but I still think your regex approach seems best

AlexDenton commented 3 years ago

For anyone curious this is what I ended up doing:

function customTelemetryInitializer(envelope) {
    const routeRegex = /(?<=\/)(\d+)/g;
    let operationName = envelope.tags['ai.operation.name'];

    if (operationName) {
        operationName = operationName.replace(routeRegex, '[id]');
        envelope.tags['ai.operation.name'] = operationName;
    }

    return true;
}