Skip to content

Instantly share code, notes, and snippets.

@rostegg
Created March 7, 2019 14:08
Show Gist options
  • Save rostegg/82184d82f71784d09290bd7356976f92 to your computer and use it in GitHub Desktop.
Save rostegg/82184d82f71784d09290bd7356976f92 to your computer and use it in GitHub Desktop.
Tiny utility for (https://gist.github.com/rostegg/4470edefb8f0098c45e035fccb90f64e) for managing logs displaying
/*
Use DEBUG variable for manage the display of logs
Define variables before init the manager and with 'var' statement
Example of usage:
var logger = new Logger('test',{ style : STYLES.RUBY_TEXT_WHITE_BACKGROUND, group : 'Test'});
var logger2 = new Logger('test2',{ style : STYLES.RUBY_TEXT_WHITE_BACKGROUND, group : 'Test2'});
...
let logManager = new LogManager();
// will display messages in "Test" group
log.showOnly(['Test'])
*/
'use strict'
var DEBUG = true;
class LogManager {
constructor (){
// it will find all declared loggers before (only 'var')
const declaredLoggers = Object.values(window).filter(value => value instanceof Logger);
this.groupCache = {};
this.excludedGroups = [];
this._initDeclaredLoggers(declaredLoggers);
}
// accept array
addExcludedGroups(group){
this.excludedGroups = this.excludedGroups.concat(group);
}
removeExcludedGroups(group){
this.excludedGroups = this._removeFromArray(this.excludedGroups, group);
}
showOnly(group){
let availableGroups = Object.getOwnPropertyNames(this.groupCache);
this.excludedGroups = this._removeFromArray(availableGroups, group);
}
_initDeclaredLoggers(list){
list.forEach(element => {
(element.group in this.groupCache) ?
this.groupCache[element.group].push(element):
this.groupCache[element.group] = [element];
this._initProxyObserver(element);
});
}
_initProxyObserver(object){
const availableMethodsNames = ['log', 'error', 'warn', 'info', 'object', 'table', 'timer'];
let self = this;
availableMethodsNames.forEach(methodName => {
object[methodName] = new Proxy(object[methodName], {
apply: function(target, thisArg, argumentsList) {
return DEBUG && !self.excludedGroups.includes(object.group) ? target.apply(thisArg, argumentsList) : null;
}
});
});
}
_removeFromArray(array, toRemove){
return array.filter(item => !toRemove.includes(item));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment