Last active
February 3, 2016 15:18
-
-
Save miguelerm/002e2ed7edf42be69fb6 to your computer and use it in GitHub Desktop.
A wrapper for console.log to listen the logged messages in a div with id "logger"
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
(function(window, console, document, undefined) { | |
var loggerId = 'logger'; | |
var log = console.log.bind(console); | |
var queue = []; | |
var logger = getLogger(); | |
console.log = customLog; | |
addEvent(window, 'load', onLoad); | |
function getLogger() { | |
return document.getElementById(loggerId); | |
} | |
function onLoad() { | |
logger = getLogger(); | |
var args = null; | |
while((args = queue.pop()) !== undefined) { | |
logToHtml.apply(this, args); | |
} | |
} | |
function logToHtml() { | |
var p = document.createElement('p'); | |
for(var argument in arguments) { | |
var span = document.createElement('span'); | |
span.innerText = JSON.stringify(arguments[argument]); | |
p.appendChild(span); | |
} | |
logger.appendChild(p); | |
} | |
function customLog() { | |
var args = arguments; | |
if (logger) { | |
logToHtml.apply(this, args); | |
} else { | |
queue.push(args); | |
} | |
log.apply(window, args); | |
} | |
function addEvent(obj, type, fn) { | |
if (obj.addEventListener) { | |
obj.addEventListener(type, fn, false); | |
} else if (obj.attachEvent) { | |
obj.attachEvent('on' + type, function() { return fn.apply(obj, new Array(window.event));}); | |
} | |
} | |
})(window, window.console, document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment