Skip to content

Commit

Permalink
[BUG] App Insights not auto-capturing from a Web Worker #1995
Browse files Browse the repository at this point in the history
  • Loading branch information
MSNev committed Mar 2, 2023
1 parent a905888 commit 617e201
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 17 deletions.
12 changes: 6 additions & 6 deletions common/config/rush/npm-shrinkwrap.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions examples/shared-worker/src/worker-npm-init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ let _appInsights: ApplicationInsights;
* @param config
* @returns
*/
export function initApplicationInsights(config: IConfiguration) {
export function initApplicationInsights(config: IConfiguration, onInitCallback: (appInsights: ApplicationInsights, port: MessagePort) => void, port: MessagePort) {

if (!_appInsights) {
// Make sure we have a configuration object
Expand All @@ -25,7 +25,11 @@ export function initApplicationInsights(config: IConfiguration) {
});

_appInsights.loadAppInsights();
_appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview
if (_appInsights.core.isInitialized()) {
// Call the callback before the trackPageView
onInitCallback(_appInsights, port);
_appInsights.trackPageView(); // Manually call trackPageView to establish the current user/session/pageview
}

return _appInsights;
}
Expand Down
41 changes: 37 additions & 4 deletions examples/shared-worker/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { initApplicationInsights, trackPageView, unloadApplicationInsights } from "./worker-npm-init";
import { ExampleMessageType, IExampleRequest, IExampleResponse } from "./interfaces/IExampleMessage";
import { IConfiguration, INotificationListener } from "@microsoft/applicationinsights-web";
import { ApplicationInsights, IConfiguration, INotificationListener } from "@microsoft/applicationinsights-web";
import { dumpObj, objAssign } from "@nevware21/ts-utils";

/**
Expand All @@ -12,7 +12,16 @@ import { dumpObj, objAssign } from "@nevware21/ts-utils";
* the connection string.
*/
const defaultApplicationInsightsConfig: IConfiguration = {

/**
* Telemtry logging level to instrumentation key. All logs with a severity
* level higher than the configured level will sent as telemetry data to
* the configured instrumentation key.
*
* 0: ALL iKey logging off
* 1: logs to iKey: severity >= CRITICAL
* 2: logs to iKey: severity >= WARNING
*/
loggingLevelTelemetry: 2
};

/**
Expand Down Expand Up @@ -91,6 +100,31 @@ function notificationListener(port: MessagePort): INotificationListener {
};
}

/**
* We only want to add any notification listener or telemetry initializer once
* otherwise they WILL get called multiple times during processing.
* @param appInsights
* @param port
*/
function onInitAddInitializers(appInsights: ApplicationInsights, port: MessagePort) {
// This callback is only called once, otherwise we would keep adding listeners and initializers
appInsights.core.getNotifyMgr().addNotificationListener(notificationListener(port));

// This is not normally needed, but this provides a view from the worker to the
// main page about errors that the worker is having / seeing
appInsights.addTelemetryInitializer((theEvent) => {
if (theEvent && theEvent.name && theEvent.name["startsWith"]("InternalMessageId") && theEvent.baseData) {
port.postMessage({
success: true,
message: "Internal Message: " + (theEvent.baseData?.message || "--")
});

// Drop ALL internal message from being sent to Azure Monitor portal
return false;
}
});
}

/**
* Initialize the SDK using the passed connection string from the request (if supplied)
* @param request
Expand All @@ -100,9 +134,8 @@ function notificationListener(port: MessagePort): INotificationListener {
function workerLoadSdk(request: IExampleRequest, port: MessagePort) {
let theConfig = objAssign({}, defaultApplicationInsightsConfig);
theConfig.connectionString = request.connectionString;
let appInsights = initApplicationInsights(theConfig);
let appInsights = initApplicationInsights(theConfig, onInitAddInitializers, port);
if (appInsights && appInsights.core.isInitialized()) {
appInsights.core.getNotifyMgr().addNotificationListener(notificationListener(port));
return {
success: true,
message: `SDK Loaded and Initialized with - ${appInsights.config.connectionString}`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
IAppInsightsCore, IDiagnosticLogger, IProcessTelemetryUnloadContext, ITelemetryUnloadState, _eInternalMessageId, _throwInternal,
arrForEach, dumpObj, eLoggingSeverity, getDocument, getExceptionName, getLocation, isNullOrUndefined
} from "@microsoft/applicationinsights-core-js";
import { isWebWorker } from "@nevware21/ts-utils";
import { PageViewPerformanceManager } from "./PageViewPerformanceManager";

/**
Expand Down Expand Up @@ -99,11 +100,13 @@ export class PageViewManager {
);
_flushChannels(true);

// no navigation timing (IE 8, iOS Safari 8.4, Opera Mini 8 - see http://caniuse.com/#feat=nav-timing)
_throwInternal(_logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.NavigationTimingNotSupported,
"trackPageView: navigation timing API used for calculation of page duration is not supported in this browser. This page view will be collected without duration and timing info.");
if (!isWebWorker()) {
// no navigation timing (IE 8, iOS Safari 8.4, Opera Mini 8 - see http://caniuse.com/#feat=nav-timing)
_throwInternal(_logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.NavigationTimingNotSupported,
"trackPageView: navigation timing API used for calculation of page duration is not supported in this browser. This page view will be collected without duration and timing info.");
}

return;
}
Expand Down

0 comments on commit 617e201

Please sign in to comment.