Reputation: 5840
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)?
Upvotes: 1
Views: 371
Reputation: 44
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
Upvotes: 0
Reputation: 7258
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"}
Fiddle: https://jsfiddle.net/mrlew/a08qL18d/
Upvotes: 1
Reputation: 31682
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...).
Upvotes: 2
Reputation: 4645
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")
https://jsfiddle.net/yak613/7g6kchox/
Upvotes: 1