Last active
December 20, 2015 07:09
-
-
Save jameshartig/6091299 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| var logger = function(level){ | |
| this.logs = []; | |
| //note: set level based on production or dev | |
| this.level = level || 3; //1 = verbose, 2 = warning, 3 = error | |
| //internal log method | |
| this._log = function(level, message) { | |
| //note: if level == 2 you could do console.warn (and remove Log Level 2:) | |
| //note: if level == 3 you could do console.error (and remove Log Level 3:) | |
| console.log(["Log level ", level, ": ", message].join("")); | |
| } | |
| }; | |
| logger.prototype.log = function (level) { | |
| var message = Array.prototype.join.call(Array.prototype.slice.call(arguments, 1), " "); | |
| if (level <= this.level) { | |
| this._log(message); | |
| return; | |
| } | |
| this.logs.push({level: level, message: message}); | |
| //todo: this should instead keep an internal "index" and then just increment that instead of checking and splicing | |
| if (this.logs.length > 50) { //onlyt keep 50 logs around | |
| this.logs = this.logs.slice(-50); | |
| } | |
| }; | |
| logger.prototype.setLogLevel = function (level) { | |
| if (level == this.level) { | |
| return; | |
| } | |
| //now that they changed the level, print out any logs from the last 50 that match this log level | |
| var skippedLogs = []; | |
| for (var i = 0, l = this.logs.length; i < l; i++) { | |
| if (this.logs[i].level > level) { | |
| skippedLogs.push(this.logs[i]); | |
| continue; | |
| } | |
| this._log(this.logs[i].message); | |
| } | |
| this.logs = skippedLogs; | |
| }; | |
| window.logger = logger; | |
| var noop = function() {}; | |
| if (!window.console) { | |
| //ie sucks | |
| window.console = { | |
| log: noop, | |
| warn: noop, | |
| error: noop | |
| }; | |
| } else if (!console.log) { | |
| //if they don't have log for some reason, they won't have any | |
| console.log = noop; | |
| console.warn = noop; | |
| console.error = noop; | |
| } |
This file contains hidden or 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
| window.myLogger = new logger(2); | |
| myLogger.log(1, "This is a log message"); | |
| myLogger.log(1, "This is a log message with a", variable, "spaces will automatically be added"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment