Is it possible to create another instance of the javascript console and use it at one's own discretion, such as placing content filed to console.log() in a div on your page)?
4 Answers
You can override it, but that's not a good practice. Like this:
console.log = function() {
for(var i = 0; i < arguments.length; i++)
document.getElementById("logs").textContent += JSON.stringify(arguments[i], null, 4) + '\n\n';
}
var object = {a: 45, b: "hh"};
console.log(object);
console.log("Hello world!");
console.log(45 + 5);
<pre id="logs"></pre>
Note 1: console.log is a great tool for debugging, it should not be overriden. I don't recommend you override it but instead, I'll recommend you make a function (called for example myConsoleLog) that does what you need.
Note 2: The example I provided is just a basic example to give you insight, you'll need a lot of other stuff (the folding of objects and arrays, the logging of functions for example...).
Comments
See this answer, which you could implement by grabbing the value of the stack and writing it to a div on your page.
<div id="log"></div>
var logBackup = console.log;
var logMessages = [];
console.log = function() {
logMessages.push.apply(logMessages, arguments);
document.getElementById('log').innerHTML = "";
for(var i = 0; i < logMessages.length; i++){
var pre = document.createElement("pre");
pre.innerHTML = logMessages[i];
document.getElementById('log').appendChild(pre);
}
logBackup.apply(console, arguments);
};
console.log("My name is joe.")
console.log("My name is tom")
2 Comments
instance of the console. The approach offered however, does work and is much appreciated.You can override console.log. Something like this:
console.log = function(objToLog) {
var myLog = document.getElementById('myLog');
var str = '';
if (typeof objToLog === 'string') {
str = objToLog;
} else if (typeof objToLog === 'object') { //includes array print
str = JSON.stringify(objToLog);
}
myLog.innerText = myLog.innerText + '\n> ' + str;
}
console.log('log this line');
console.log('log this other line');
console.log([1,2,3]);
console.log({ key: 'value' });
Will print to a div:
> log this line
> log this other line
> [1,2,3]
> {"key":"value"}
Comments
Is it possible to create another instance of the javascript console
In browser, consoles cannot be instantiated. Only one instance exists. So to group data together you need to create new own separate method which will save all messages and output them into some place.
In Node.JS you can create new instances of Console class and set out/err streams for new instance.
https://nodejs.org/api/console.html#new-consolestdout-stderr-ignoreerrors