Skip to content

Instantly share code, notes, and snippets.

@ShawInnes
Created February 15, 2021 03:58
Show Gist options
  • Save ShawInnes/acd992de5301d2d351cc51aad01dc958 to your computer and use it in GitHub Desktop.
Save ShawInnes/acd992de5301d2d351cc51aad01dc958 to your computer and use it in GitHub Desktop.
ReactCorrelation
import { ApplicationInsights, ITelemetryItem } from '@microsoft/applicationinsights-web';
import { ReactPlugin } from '@microsoft/applicationinsights-react-js';
import { createBrowserHistory } from 'history';
const reactPlugin = new ReactPlugin();
const browserHistory = createBrowserHistory({ basename: '' });
const createApplicationInsights = () => {
if (process.env.REACT_APP_ApplicationInsights_InstrumentationKey && process.env.REACT_APP_ApplicationInsights_InstrumentationKey !== '') {
const ai = new ApplicationInsights({
config: {
instrumentationKey: process.env.REACT_APP_ApplicationInsights_InstrumentationKey,
extensions: [reactPlugin],
enableAutoRouteTracking: true,
extensionConfig: {
[reactPlugin.identifier]: {
debug: true,
history: browserHistory
}
}
}
});
ai.loadAppInsights();
ai.addTelemetryInitializer(item => {
item.tags = item.tags ?? [];
item.tags['ai.cloud.role'] = 'admin-portal';
item.tags['ai.application.ver'] = process.env.REACT_APP_Version ?? '1.0.0-undefined';
});
return ai;
}
return null;
};
const applicationInsightsInstance = createApplicationInsights();
const appInsights: ApplicationInsights | null = applicationInsightsInstance;
/*
The following code block injects an initializer to replace the default page title in Application Insights
with a more suitable uri-based string, stripped of uniqueness
- removes http(s)://hostname(:port)
- removes querystrings
- removes guids
- removes numbers
*/
appInsights?.addTelemetryInitializer((telemetryItem: ITelemetryItem) => {
try {
if (telemetryItem && telemetryItem.baseData) {
let url = telemetryItem.baseData.uri;
url = url.replace(/(http|https):\/\/([a-z0-9\-\.:]*)/i, '');
url = url.replace(/(\?.*$)/i, '');
url = url.replace(/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/i, '...');
url = url.replace(/([0-9]+)/i, '...');
telemetryItem.baseData.name = url;
}
} catch (e) {
// silently fail, we don't want telemetry breaking things
}
});
export { reactPlugin, appInsights };
export const getAxiosInstance = async (userProfileId: UserProfileId) => {
const user = await userManager.getUser();
const token = user?.id_token;
return axios.create({
headers: {
Authorization: `Bearer ${token}`,
'X-version': 1,
'x-userprofile-id': userProfileId,
'x-correlation-id': uuidv4()
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment