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-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.
Event:
Exception:
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
Leave a comment