Refactor logger.js

This commit is contained in:
SleepWalker 2018-05-02 20:48:50 +03:00
parent fde1d36287
commit e7923fc1b8

View File

@ -1,3 +1,5 @@
// @flow
import type {User} from 'components/user';
import Raven from 'raven-js'; import Raven from 'raven-js';
import abbreviate from './abbreviate'; import abbreviate from './abbreviate';
@ -5,8 +7,8 @@ import abbreviate from './abbreviate';
const isTest = process.env.__TEST__; // eslint-disable-line const isTest = process.env.__TEST__; // eslint-disable-line
const isProduction = process.env.__PROD__; // eslint-disable-line const isProduction = process.env.__PROD__; // eslint-disable-line
const logger = { class Logger {
init({sentryCdn}) { init({ sentryCdn }: { sentryCdn: string }) {
if (sentryCdn) { if (sentryCdn) {
Raven.config(sentryCdn, { Raven.config(sentryCdn, {
logger: 'accounts-js-app', logger: 'accounts-js-app',
@ -37,33 +39,42 @@ const logger = {
message = ''; message = '';
} }
logger.info(`Unhandled rejection${message}`, { this.info(`Unhandled rejection${message}`, {
error, error,
event event
}); });
}); });
} }
}, }
setUser(user) { setUser(user: User) {
Raven.setUserContext({ Raven.setUserContext({
username: user.username, username: user.username,
email: user.email, email: user.email,
id: user.id id: user.id
}); });
} }
};
[ error(message: string | Error, context: Object) {
// 'fatal', log('error', message, context);
'error', }
'warning',
'info', info(message: string | Error, context: Object) {
'debug' log('info', message, context);
].forEach((level) => { }
const method = level === 'warning' ? 'warn' : level;
warn(message: string | Error, context: Object) {
log('warning', message, context);
}
}
function log(
level: 'error' | 'warning' | 'info' | 'debug',
message: string | Error,
context: Object
) {
const method: 'error' | 'warn' | 'info' | 'debug' = level === 'warning' ? 'warn' : level;
logger[method] = (message, context) => {
if (isTest) { if (isTest) {
return; return;
} }
@ -80,11 +91,10 @@ const logger = {
Raven.captureException(message, { Raven.captureException(message, {
level, level,
extra: context extra: context,
}); });
}); });
}; }
});
/** /**
* prepare data for JSON.stringify * prepare data for JSON.stringify
@ -93,7 +103,7 @@ const logger = {
* *
* @return {Promise} * @return {Promise}
*/ */
function prepareContext(context) { function prepareContext(context: any) {
if (context instanceof Response) { if (context instanceof Response) {
// TODO: rewrite abbreviate to use promises and recursively find Response // TODO: rewrite abbreviate to use promises and recursively find Response
return context.json() return context.json()
@ -120,4 +130,4 @@ function prepareContext(context) {
return Promise.resolve(abbreviate(context)); return Promise.resolve(abbreviate(context));
} }
export default logger; export default new Logger();