TrackEvent do Application Insights nunca persistiu no Azure

Dec 17 2020

Estou tentando implementar o SDK para Node para rastrear eventos personalizados em nossa base de código. O serviço que escrevi é chamado de uma cadeia de método assíncrono e executado no Azure Functions:

public async handleEvent(event: Event) {
    // Do stuff

    // Then report event
    this.reportEvent(event);
}

private reportEvent(event: Event) {
    if (this._applicationInsightsService) {
        this._applicationInsightsService.reportEvent(event)
        this._context.log("Successfully sent event to application insights")
    } else {
        this._context.log("Could not send metrics to application insights, service is not defined")
    }
}

O serviço em si é assim:

export class ApplicationInsightsService {

    private _instance: ApplicationInsights

    private constructor(connectionString: string) {
        this._instance = new ApplicationInsights({ 
            config: {
                connectionString: connectionString
            } 
        })
        this._instance.loadAppInsights()
    }

    public static create() {
        if (process.env.APPLICATION_INSIGHTS_CONNECTION_STRING === undefined) {
            throw new Error("APPLICATION_INSIGHTS_CONNECTION_STRING undefined, cannot report metrics")
        }
        return new ApplicationInsightsService(process.env.APPLICATION_INSIGHTS_CONNECTION_STRING)
    }

    public reportEvent(event: Event) {
        this._instance.trackEvent({
            name: event.type,
            properties: event
        })
        this._instance.flush()
    }
}

No entanto, os eventos que envio nunca são visíveis no Portal do Azure quando eu consulto a customEventstabela. Esperei por> 10 minutos, pois sei que pode haver atrasos nos insights do aplicativo.

Eu tentei fazer a chamada para liberar assíncrono em vez disso e usar awaitao chamá-lo, mas isso também não ajuda:

Promise.resolve(this._instance.flush(true))

A variável de ambiente APPLICATION_INSIGHTS_CONNECTION_STRINGtem o formato InstrumentationKey=xxx;IngestionEndpoint=https://westeurope-1.in.applicationinsights.azure.com/.

Meu problema parece muito semelhante à falha do C # Application Insight: TrackEvent Não envia para o Azure Application Insight , mas eu realmente preciso dormir / tempo limite para contabilizar os tempos?

A saída do log quando eu executo isso não diz nada, nenhum erro foi produzido e nada parece errado:

[12/17/2020 11:06:10 AM] Executing 'Functions.EventHandler' (Reason='New ServiceBus message detected on 'integrator-events'.', Id=812ccf8f-3cd3-4c75-8ab4-20614556d597)
[12/17/2020 11:06:10 AM] Trigger Details: MessageId: 125f60d79c5a4b029a417bee68df95d7, DeliveryCount: 1, EnqueuedTime: 12/17/2020 11:06:11 AM, LockedUntil: 12/17/2020 11:07:11 AM, SessionId: (null)
[12/17/2020 11:06:10 AM] Received event
[12/17/2020 11:06:10 AM] Successfully sent event to application insights
[12/17/2020 11:06:10 AM] Executed 'Functions.EventHandler' (Succeeded, Id=812ccf8f-3cd3-4c75-8ab4-20614556d597)

o que estou perdendo?

Atualizar

Então, aparentemente, há um JavaScript e um Node SDK para tornar as coisas mais confusas. Vou tentar com o SDK do Node, mas não vejo por que o anterior não deve funcionar.

Solução

A seguinte construção do ApplicationInsightsService funciona:

// Previously:
// import { ApplicationInsights } from "@microsoft/applicationinsights-web"
import { TelemetryClient } from "applicationinsights"

export class ApplicationInsightsService {

    private _instance: TelemetryClient

    private constructor(connectionString: string) {
        this._instance = new TelemetryClient(connectionString)
    }
}

Para aplicativos de nó:

Faça :npm install --save applicationinsights

Não :npm install --save @microsoft/applicationinsights-web

Respostas

jokarl Dec 17 2020 at 18:42

A seguinte construção das ApplicationInsightsServiceobras:

// Previously:
// import { ApplicationInsights } from "@microsoft/applicationinsights-web"
import { TelemetryClient } from "applicationinsights"

export class ApplicationInsightsService {

    private _instance: TelemetryClient

    private constructor(connectionString: string) {
        this._instance = new TelemetryClient(connectionString)
    }
}

Para aplicativos de nó:

Faça :npm install --save applicationinsights

Não :npm install --save @microsoft/applicationinsights-web