Last active
October 1, 2021 20:21
-
-
Save imran3/5d41b960bac7bfaca13aaf426f3cf826 to your computer and use it in GitHub Desktop.
Application Insights snippet for Angular apps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class MyComponent { | |
constructor(private applicationInsightsService: ApplicationInsightsService) {} | |
interestingEventHappens(data: EventData): void { | |
ApplicationInsightsService.logEvent("event-name", data); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- the snippet below assumes that JS SDK script has already loaded --> | |
<script type="text/javascript" src="/path/to/ai-js-sdk.js"></script> | |
<script type="text/javascript"> | |
var snippet = { | |
config: { | |
instrumentationKey: "INSTRUMENTATION_KEY" // replace with key from Azure portal | |
} | |
}; | |
var init = new Microsoft.ApplicationInsights.ApplicationInsights(snippet); | |
var appInsights = init.loadAppInsights(); | |
appInsights.trackPageView(); // send page view data to azure portal | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(n){var o={config:n,initialize:!0},t=document,e=window,i="script";setTimeout(function(){var e=t.createElement(i);e.src=n.url||"https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js",t.getElementsByTagName(i)[0].parentNode.appendChild(e)});try{o.cookie=t.cookie}catch(e){}function a(n){o[n]=function(){var e=arguments;o.queue.push(function(){o[n].apply(o,e)})}}o.queue=[],o.version=2;for(var s=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];s.length;)a("track"+s.pop());var r="Track",c=r+"Page";a("start"+c),a("stop"+c);var u=r+"Event";if(a("start"+u),a("stop"+u),a("addTelemetryInitializer"),a("setAuthenticatedUserContext"),a("clearAuthenticatedUserContext"),a("flush"),o.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4},!(!0===n.disableExceptionTracking||n.extensionConfig&&n.extensionConfig.ApplicationInsightsAnalytics&&!0===n.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){a("_"+(s="onerror"));var p=e[s];e[s]=function(e,n,t,i,a){var r=p&&p(e,n,t,i,a);return!0!==r&&o["_"+s]({message:e,url:n,lineNumber:t,columnNumber:i,error:a}),r},n.autoExceptionInstrumented=!0}return o}( | |
{ | |
instrumentationKey:"INSTRUMENTATION_KEY" // replace with key from Azure portal | |
} | |
);(window[aiName]=aisdk).queue&&0===aisdk.queue.length&&aisdk.trackPageView({}); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Injectable() | |
export class ApplicationInsightsErrorHandler extends ErrorHandler { | |
constructor(private injector: Injector) { | |
super(); | |
} | |
handleError(error: any): void { | |
// injecting ApplicationInsightService via injector to avoid infinite loop in case | |
// error is with service itself | |
this.injector.get<ApplicationInsightsService>(ApplicationInsightsService).logException(error); | |
super.handleError(error); // optional | |
// add any customer error handling here | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { ApplicationInsights } from '@microsoft/applicationinsights-web'; | |
@Injectable() | |
export class ApplicationInsightsService { | |
appInsights: ApplicationInsights; | |
constructor() { | |
const appInsightsKey = "INSTRUMENTATION_KEY"; // DO NOT HARDCODE KEY HERE, use AppConfigService or a better approach | |
if (!appInsightsKey) { | |
// add custom behavior to handle this scenario | |
console.error('Application Insights key not found.'); | |
return; | |
} | |
this.appInsights = new ApplicationInsights({ | |
config: { | |
instrumentationKey: appInsightsKey, | |
enableAutoRouteTracking: true, // optional: auto-log all route changes | |
}, | |
}); | |
this.appInsights.loadAppInsights(); | |
} | |
// helper methods to track a variety of events and metric | |
logPageView(name?: string, url?: string) { | |
this.appInsights.trackPageView({ | |
name: name, | |
uri: url, | |
}); | |
} | |
logEvent(name: string, properties?: { [key: string]: any }) { | |
this.appInsights.trackEvent({ name: name }, properties); | |
} | |
logMetric(name: string, average: number, properties?: { [key: string]: any }) { | |
this.appInsights.trackMetric({ name: name, average: average }, properties); | |
} | |
logException(exception: Error, severityLevel?: number) { | |
this.appInsights.trackException({ exception: exception, severityLevel: severityLevel }); | |
} | |
logTrace(message: string, properties?: { [key: string]: any }) { | |
this.appInsights.trackTrace({ message: message }, properties); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment