@rockpack/logger
Version:
This module can help you build error tracking & crash reporting system for your React application.
68 lines (67 loc) • 1.98 kB
JavaScript
import { isFunction } from 'valid-types';
import LimitedArray from 'limited-array';
/**
* Types:
* log
* info
* warn
* error
* debug
* */
class Logger {
constructor() {
this.active = true;
this.stdout = null;
this.ignoreLogging = false;
this._count = 0;
this.getCounter = () => this._count;
this.getStackCollection = () => this.stackCollection;
this.stackCollection = new LimitedArray();
}
log(message, important) {
this._handler(message, 'log', !!important);
}
info(message, important) {
this._handler(message, 'info', !!important);
}
debug(message, important) {
this._handler(message, 'debug', !!important);
}
warn(message, important) {
this._handler(message, 'warn', !!important);
}
error(message, important) {
this._handler(message, 'error', !!important);
}
setUp(props) {
if (typeof props.active === 'boolean') {
this.active = Boolean(props.active);
}
if (typeof props.stdout === 'function') {
this.stdout = props.stdout;
}
}
_handler(message, level, important) {
if (!this.ignoreLogging &&
this.active) {
if (isFunction(this.stdout)) {
this.stdout(level, message, important);
}
let stackData;
if (typeof message === 'string') {
const temp = {};
temp[level] = message;
stackData = temp;
}
else if (typeof message === 'object') {
stackData = message;
}
if (stackData) {
this.stackCollection.add(Object.assign({}, stackData));
}
this._count += 1;
}
}
}
export const createLogger = () => new Logger();
export const logger = createLogger();