Skip to content

Instantly share code, notes, and snippets.

@shannon
Last active February 18, 2020 19:05
Show Gist options
  • Select an option

  • Save shannon/3f169b8e88bb05da346ed14736d8b0e5 to your computer and use it in GitHub Desktop.

Select an option

Save shannon/3f169b8e88bb05da346ed14736d8b0e5 to your computer and use it in GitHub Desktop.
Adding simple log levels to console logging

Example:

import log from './simple-log.js'

log.level = 'info';

log.trace('should NOOP');
log.debug('should NOOP');
log.info('should output');
log.log('should output');
log.warn('should output');
log.error('should output');


log.level = 'silent';

log.trace('should NOOP');
log.debug('should NOOP');
log.info('should NOOP');
log.log('should NOOP');
log.warn('should NOOP');
log.error('should NOOP');
const NOOP = () => {};
const LEVELS = [
'trace',
'debug',
'info',
'log',
'warn',
'error',
'silent',
];
const _ = new WeakMap();
export class Log {
constructor(level = 'info') {
_.set(this, {});
this.level = level;
}
get level() {
return _.get(this).level;
}
set level(value) {
const index = LEVELS.findIndex(level => level === value);
if(index === -1) throw new Error('Invalid log level');
for(let i = 0; i < index; i++){
this[LEVELS[i]] = NOOP;
}
for(let i = index; i < LEVELS.length - 1; i++) {
this[LEVELS[i]] = console[LEVELS[i]];
}
_.get(this).level = value;
}
}
export default new Log();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment