Last active
August 1, 2018 08:24
-
-
Save rostegg/0f3b42dee9fc657fd4c36a6a8f843ef2 to your computer and use it in GitHub Desktop.
Simple console logger with custom css styles and tree-style displaying objects
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
(function () { | |
this.Logger = function(){ | |
var defaults = { | |
style : 'background: white; color: black; display: block;', | |
tag: 'DEFAULT' | |
}; | |
if (arguments[0] && typeof arguments[0] === "object") { | |
this.options = _extendDefaults(defaults, arguments[0]); | |
} | |
this.message_template = `%c${_time()} [${this.options.tag}]:`; | |
}; | |
Logger.prototype = { | |
debug : function(message){ | |
console.debug(`${this.message_template} ${message}`, this.options.style); | |
}, | |
error : function(message){ | |
console.error(`${this.message_template} ${message}`, this.options.style); | |
}, | |
log : function(message){ | |
console.log(`${this.message_template} ${message}`, this.options.style); | |
}, | |
warn : function(message){ | |
console.warn(`${this.message_template} ${message}`, this.options.style); | |
}, | |
object : function (name, obj){ | |
console.log(`${this.message_template}`, this.options.style); | |
console.groupCollapsed(`%cObject \'${name}\'`,this.options.style); | |
_outputObject("",obj,this.options.style); | |
console.groupEnd(); | |
}, | |
}; | |
var _outputObject = function(name,obj,style) { | |
var property; | |
for (property in obj) { | |
if (!_isObject(obj[property])) | |
console.log(`%c${property}: ${obj[property]}`,style); | |
else { | |
console.groupCollapsed(`%c${property}`,style); | |
_outputObject(property,obj[property],style); | |
} | |
} | |
if (name != "" || name != undefined) | |
console.groupEnd(); | |
}; | |
var _isObject = function (val) { | |
if (val === null) { return false;} | |
// without arrays | |
return ( (typeof val === 'function') || (typeof val === 'object') && !(Array.isArray(val)) ); | |
}; | |
var _extendDefaults = function (source, properties) { | |
var property; | |
for (property in properties) { | |
if (properties.hasOwnProperty(property)) { | |
source[property] = properties[property]; | |
} | |
} | |
return source; | |
}; | |
var _time = function () { | |
return (`[${new Date().toISOString()}]`); | |
}; | |
}()); | |
/* | |
Example of usage | |
var logger = new Logger( { style : 'background: green; color: white; display: block;'}); | |
logger.debug("test"); | |
// display options object | |
logger.object("Options", logger.options); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment