Created
July 5, 2017 15:53
-
-
Save loopmode/e537a00770c7d2291adf0d3567d52ef7 to your computer and use it in GitHub Desktop.
A console logger with name prefix and persisted enable/disable functionality.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A console logger with name prefix and persisted enable/disable functionality. | |
* Disabled by default. | |
* Enabled/disabled state is persisted in browser storage, e.g. localStorage or sessionStorage, and survives page refresh. | |
* @example: | |
* this.logger = new Logger({name: 'Grid'}); this.logger.log('Yay!'); | |
*/ | |
function Logger(options) { | |
options = options || {}; | |
var name = options.name || 'default'; | |
var lsKey = 'Logger.' + name + '.enabled'; | |
var storage = options.storage || window.localStorage; | |
var enabled = storage.getItem != undefined && !!storage.getItem(lsKey); | |
var consolefn = function (fn, args) { | |
if (enabled) { | |
console[fn].apply(console, ['[' + name + ']'].concat([].slice.call(args))); | |
} | |
}; | |
this.enable = function () { | |
enabled = true; | |
storage.setItem(lsKey, true); | |
}; | |
this.disable = function () { | |
enabled = false; | |
storage.removeItem(lsKey); | |
}; | |
this.log = function () { | |
consolefn('log', arguments); | |
}; | |
this.warn = function () { | |
consolefn('warn', arguments); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment