Skip to content

Instantly share code, notes, and snippets.

@ozkary
Last active March 22, 2022 14:39
Show Gist options
  • Save ozkary/b3e4aba6d1fb5607dda69361cce290d4 to your computer and use it in GitHub Desktop.
Save ozkary/b3e4aba6d1fb5607dda69361cce290d4 to your computer and use it in GitHub Desktop.
AppInsights React Logger Service
// import the operations from logger
import { error, audit } from '../logger';
/**
* Sample code to log an error from a handled exception
* send the message asychronously
*/
try {
// call an operation that can raise errors
}catch(err) {
error(err);
}
/**
* log a validation error
*/
const err = new Error('Validation failed');
error(err);
// import the operations from logger
import { audit } from './logger';
/**
* Sample code to log a custom event with a string value
* replace event-tag with a meaningful tag value
*/
await audit<string>('event-tag', 'some value or message');
/**
* Sample code to log a custom event with a json doc
* replace event-tag with a meaningful tag value
*/
/**
* Define a custom event message
* send the message asychronously
*/
interface CustomEvent {
id: string;
message: string;
}
// build the message
const event: CustomEvent = {
id: 123,
message: 'hi from client app'
};
audit<CustomEvent>('event-tag', event);
/**
* @file logger.ts
* @description Send errors and custom events to AppInsights
* @author ogarcia (ozkary.com)
*/
import {
ApplicationInsights,
SeverityLevel
} from '@microsoft/applicationinsights-web';
/**
* Create the appInsights instance
* Read the instrumentation key from the .env file
*/
const appInsights = new ApplicationInsights({
config: {
instrumentationKey: process.env.REACT_APP_INSIGHTSKEY,
enableAutoRouteTracking: true
}
});
/**
* initialize the app insight service
*/
const init = async (): Promise<void> => {
if (process.env.REACT_APP_Insights && appInsights) {
appInsights.loadAppInsights();
}
};
/**
* send errors to AppInsights
* @param error error object
*/
const error = async (error: Error): Promise<void> => {
if (appInsights){
const ex = {
error,
severityLevel: SeverityLevel.Error
}
appInsights.trackException(ex);
}
};
/**
* log a custom telemetry event
* @param name the dimension to report
* @param doc the json document or a message
*/
const track = async <T>(name: string, doc: T): Promise<void> => {
const msg = JSON.stringify(doc);
if (appInsights) {
appInsights.trackEvent({ name }, { message: msg });
}
};
/** export the operations */
export { error, track };
/**
* Initialize the service
*/
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment