Skip to content

Instantly share code, notes, and snippets.

@elrac
Last active August 29, 2015 14:26
Show Gist options
  • Save elrac/87deb9181e2c63a35bef to your computer and use it in GitHub Desktop.
Save elrac/87deb9181e2c63a35bef to your computer and use it in GitHub Desktop.
A js script for printing console logs on the page as well as in the console.
(function () {
// add a div with id='consoleLog' to the document and
// it will have the console log in it. If that div doesn't
// exist then this code does nothing.
var style = document.createElement('style');
style.setAttribute("type", "text/css");
style.textContent = ".info{background-color:lightGreen;}.warn{background-color:yellow}.error{background-color:lightPink}#consoleLog{border:medium double;}";
document.querySelector('head').appendChild(style);
['log', 'info', 'warn', 'error'].forEach(function (verb) {
console[verb] = (function (method, verb) {
return function () {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
method.apply(console[verb], args);
var log = document.querySelector('#consoleLog');
if (log) {
var text = args.reduce(function (previous, current) {
var txt = current;
if (typeof current === 'object') {
txt = JSON.stringify(current);
}
return previous + ' ' + txt;
}, '');
var msg = document.createElement('code');
msg.classList.add(verb);
msg.textContent = verb + ': ' + text;
log.appendChild(msg);
log.appendChild(document.createElement('br'));
}
};
})(console[verb].bind(console), verb);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment