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