Skip to content

Instantly share code, notes, and snippets.

@eloypnd
Last active July 17, 2018 22:39
Show Gist options
  • Save eloypnd/35d7f89f031a36bf6d48a47486b3aace to your computer and use it in GitHub Desktop.
Save eloypnd/35d7f89f031a36bf6d48a47486b3aace to your computer and use it in GitHub Desktop.
/**
* @module utils/logger
*/
/**
* Object from Sentry SDK
* @see {@link https://docs.sentry.io/clients/javascript/}
*
* Raven (Sentry SDK) is expected to be loaded directly from their CDN.
* Or you can instead use npm pkg: [raven-js]{@link https://github.com/getsentry/raven-js}
*
* Reason for this setup is performance: js bundle are usually quite big in modern websites.
* If code-splitting is properly implemented, then using npm pkg is a better option.
*
* @type {Object}
*/
const Raven = window.Raven;
const LOG_LEVELS = [
'error',
'warn',
'log',
'info',
'debug',
'assert',
'dir',
'profile',
'profileEnd'
];
const __DEV__ = process.env.NODE_ENV !== 'production';
const SENTRY_DSN = process.env.REACT_APP_SENTRY_DSN;
export const init = () => {
if (SENTRY_DSN && Raven && !__DEV__) {
Raven.config(SENTRY_DSN).install();
// if you want to identify user
// Raven.setUserContext({ id: ''});
}
};
/**
* @example
* logger('error', new Error('Somehting happened!', {
* logger: '',
* tags: {},
* extra: any
* }))
*
* @func logger
* @param {string} level
* @param {string|Error} message
* @param {object} additionalData
*/
function logger () {
const args = Array.prototype.slice.call(arguments);
// first param can be optionaly the log level
let level = LOG_LEVELS.every(elem => !(elem === args[0]))
? 'info'
: args.shift();
if (__DEV__) {
// check if console[level] is a method of object console <- To be ignored by IE9 and lower
if (typeof console === 'object' && console[level] && console[level].apply) {
console[level].apply(console, args);
}
}
// Send log to Sentry
if (SENTRY_DSN && Raven && !__DEV__) {
Raven.captureMessage(args[0], Object.assign({ level: level }, args[1]));
}
}
export default logger;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment