Application Insights TrackEvent nunca persistió en Azure

Dec 17 2020

Estoy tratando de implementar el SDK para Node para rastrear eventos personalizados en nuestra base de código. El servicio que escribí se llama desde una cadena de métodos asincrónicos y se ejecuta en 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")
    }
}

El servicio en sí tiene este aspecto:

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()
    }
}

Sin embargo, los eventos que envío nunca son visibles en Azure Portal cuando consulto la customEventstabla. He esperado más de 10 minutos porque sé que puede haber retrasos en la información de la aplicación.

Intenté hacer la llamada para vaciar asincrónico en su lugar y usarlo awaital llamarlo, pero eso tampoco ayuda:

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

La variable de entorno APPLICATION_INSIGHTS_CONNECTION_STRINGtiene el formato InstrumentationKey=xxx;IngestionEndpoint=https://westeurope-1.in.applicationinsights.azure.com/.

Mi problema parece muy similar a C # Application Insight Failure: TrackEvent no se envía a Azure Application Insight , pero ¿ realmente necesito dormir / desconectar para tener en cuenta los tiempos?

La salida del registro cuando ejecuto esto no dice nada, no se producen errores y nada parece apagado:

[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)

¿Qué me estoy perdiendo?

Actualizar

Entonces, aparentemente, hay un JavaScript y un Node SDK para hacer las cosas más confusas. Lo intentaré con el SDK de Node, pero no veo por qué el primero no debería funcionar.

Solución

La siguiente construcción del 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 aplicaciones de nodo:

Hacer :npm install --save applicationinsights

No :npm install --save @microsoft/applicationinsights-web

Respuestas

jokarl Dec 17 2020 at 18:42

La siguiente construcción de las 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 aplicaciones de nodo:

Hacer :npm install --save applicationinsights

No :npm install --save @microsoft/applicationinsights-web