How to get console.log contents as string in JavaScript

I am trying to get console.log as a string in pure JavaScript. My input is a script that I am not familiar with, and I want to collect all the messages in console.log into a string.

For example:

function doSomething(){ console.log("start"); console.log("end"); var consoleLog = getConsoleLog(); return consoleLog; } function getConsoleLog(){ // How to implement this? } alert(doSomething()); 

JSFiddle link

Please note that I do not need to warn the log - this is just a simple example of testing functionality. I will need to do some operations on the contents of the log.

+8
javascript logging console
source share
1 answer

You can overwrite the console.log method before using it:

 var logBackup = console.log; var logMessages = []; console.log = function() { logMessages.push.apply(logMessages, arguments); logBackup.apply(console, arguments); }; 

Using apply and arguments preserves the correct behavior of console.log , i.e. You can add multiple log messages with a single call.

It will move all new console.log messages to the logMessages array.

+13
source share

All Articles