How to Implement Logging and Exception Handling using Azure Application Insights in SPFx WebParts

Sathish Nadarajan
 
Solution Architect
May 21, 2020
 
Rate this article
 
Views
3101

Let us see how to log the custom events and exceptions in SPFx webparts using Azure AppInsights.
To start with, let us create an Application Insight Service in the Azure Portal.

Once, it got created, make a note of Instrumentation Key.

With this, we are done with the Creation of App Insight. Now, let us go to our SPFx WebPart.
1. Install the packages @microsoft/applicationinsights-web, @microsoft/applicationinsights-react-js by using the below commands from the Terminal.

npm i @microsoft/applicationinsights-web –save
npm i @microsoft/applicationinsights-react-js –save

2. Create a new TS file with the below code.

import { ApplicationInsights } from '@microsoft/applicationinsights-web'
import { ReactPlugin, withAITracking } from '@microsoft/applicationinsights-react-js'
import { globalHistory } from "@reach/router"

let appInsightsKey : string = "<<The Copied Instrumentation Key>>";
const reactPlugin = new ReactPlugin();
const ai = new ApplicationInsights({
    config: {
        instrumentationKey: appInsightsKey,
        extensions: [reactPlugin],
        extensionConfig: {
            [reactPlugin.identifier]: { history: globalHistory }
        }
    }
})
ai.loadAppInsights()

export default (Component) => withAITracking(reactPlugin, Component)
export const appInsights = ai.appInsights

3. And in the Webpart or in any of the components file, use the below lines to record the events and exceptions.

import { appInsights } from ‘../components/mycomponent/AppInsights’

Event:

appInsights.trackEvent({ name: ‘My Custom Events’, properties: {component:” WebPart”, message: “WebPart Loaded Now” } });

Exception:

try {
throw “Exception Thrown Now”;
}
catch (err) {
appInsights.trackException({exception: new Error(“My Exception”), severityLevel:SeverityLevel.Error, properties:{component:” WebPart”, method:”onInit”, err }});
}

4. Now, let us go back to our AppInsights and we can see the entries on the Log Analytics Section.

Happy Coding
Sathish Nadarajan

Category : Office 365, SharePoint, SPFx

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment