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)?
Asked
Active
Viewed 287 times
1

SquareCat
- 5,699
- 9
- 41
- 75
3 Answers
2
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...).

ibrahim mahrir
- 31,174
- 5
- 48
- 73
1
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")
-
Thank You. You came first, so your answer is accepted – please note though that none of the given answers offer a straight answer to the actual question – whether it's possible to create another `instance` of the console. The approach offered however, does work and is much appreciated. – SquareCat Feb 05 '17 at 06:00
-
You might want to look at [console profiles](https://developers.google.com/web/tools/chrome-devtools/console/console-reference?utm_source=dcc&utm_medium=redirect&utm_campaign=2016q3#profile). Note that this reference is only for Chrome. – yaakov Feb 05 '17 at 06:06
1
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"}

mrlew
- 7,078
- 3
- 25
- 28