65

I'm building a debugging tool for my web app and I need to show console errors in a div. I know I can use my own made console like object and use it, but for future use I need to send all console errors to window. Actually I want to catch console events.

3

8 Answers 8

79

To keep the console working:

if (typeof console  != "undefined") 
    if (typeof console.log != 'undefined')
        console.olog = console.log;
    else
        console.olog = function() {};

console.log = function(message) {
    console.olog(message);
    $('#debugDiv').append('<p>' + message + '</p>');
};
console.error = console.debug = console.info =  console.log
3
  • 1
    Just thinking that check for != "undefined" is only partially complete, later on we are assigning to console.log anyway... Jan 27, 2017 at 15:55
  • 11
    For those where this solution is not working: Have you considered, that this solution required jQuery becuase of this selector $('#debugDiv') ? Try using something like this instead: document.getElementById('debugDiv').innerHTML += ('<p>' + message + '</p>');
    – Smamatti
    Apr 15, 2018 at 7:56
  • What about ReferenceErrors?
    – Tooraj Jam
    May 6 at 11:25
34

Here's a way using closure, containing the old console log function in the scope of the new one.

console.log = (function (old_function, div_log) { 
    return function (text) {
        old_function(text);
        div_log.value += text;
    };
} (console.log.bind(console), document.getElementById("error-log")));
5
  • 4
    I got it working by using div_log.textContent += text;
    – srgsanky
    Oct 17, 2015 at 15:53
  • Adding console.error = console.log = (function... made mine work for errors. This could work for other console.[whatever] as well. Also @srgsanky's change was required for it to work on mine. Feb 2, 2017 at 0:26
  • Yeah textContent definitely looks like it is the right attribute to use today. Justin - when you override a browser API, usually you want to store a reference to and call the API, so your new function that you assign should still be calling the old console.error or console.log function. I don't think that can be done if you set multiple attrs with one function - will need multiple functions.
    – MST
    Dec 29, 2017 at 21:43
  • this works! but by using div_log.innerHTML += text + '<br />'; will be more clear
    – Amos
    Mar 29, 2019 at 7:29
  • what do you mean old console . I don't get multiple console in single function . your code same as pinned answer . if (typeof console !== 'undefined') { if (typeof console.log !== 'undefined') { console.log = (function (old_function) { return function (text) { old_function(text); const newMessage = text.replace('%c', ''); setMessage([...message, newMessage]); }; })(console.log.bind(console)); } Apr 4 at 10:53
18

None of the answers here consider console messages that get passed multiple parameters. E.g. console.log("Error:", "error details")).

The function that replaces the default log function better regards all function arguments (e.g. by using the arguments object). Here is an example:

console.log = function() {
  log.textContent += Array.prototype.slice.call(arguments).join(' ');
}

(The Array.prototype.slice.call(...) simply converts the arguments object to an array, so it can be concatenated easily with join().)

When the original log should be kept working as well:

console.log = (function (old_log, log) { 
    return function () {
        log.textContent += Array.prototype.slice.call(arguments).join(' ');
        old_log.apply(console, arguments);
    };
} (console.log.bind(console), document.querySelector('#log')));
  

A complete solution:

var log = document.querySelector('#log');
['log','debug','info','warn','error'].forEach(function (verb) {
    console[verb] = (function (method, verb, log) {
        return function () {
            method.apply(console, arguments);
            var msg = document.createElement('div');
            msg.classList.add(verb);
            msg.textContent = verb + ': ' + Array.prototype.slice.call(arguments).join(' ');
            log.appendChild(msg);
        };
    })(console[verb], verb, log);
});

(An example of a framework that emits messages with multiple parameters is Video.js. But there is certainly many others.)

Edit: Another use of multiple parameters is the formatting capabilities of the console (e.g. console.log("Status code: %d", code).

About errors that are not shown

(Update Dec. 2021)

If any code crashes with an uncaught error, in might not show up in the div. One solution could be, if possible, to wrap all code in a try block to catch such errors and log them manually to the div.

try {
    // Code that might throw errors...
} catch(err) {
    // Pass the error to the overridden error log handler
    console.error(err);
}
5
  • +1. This is a more thoughtful answer than most. But it would be even better if you could somehow output JSON.stringify() result for each of the arguments, since often they will be objects. Currently it's just outputting [object Object], and I haven't yet figured out where to use JSON.stringify() in your code. Thanks for the start, though.
    – Ryan
    Apr 5, 2018 at 3:05
  • It also took me a while to realize that I needed to place your code within $(document).ready(function () { ... });
    – Ryan
    Apr 5, 2018 at 3:05
  • 2
    Ahhh I think msg.textContent = verb + ' ' + JSON.stringify(Array.prototype.slice.call(arguments)); works.
    – Ryan
    Apr 5, 2018 at 3:25
  • 4
    This is the closest to what I'm looking for. Though I still can't get errors like Uncaught ReferenceError, GET errors or any other that appear on console. Is there any way we can return ANY error, live?
    – Igor O
    May 2, 2018 at 3:28
  • How can I get multiple console. I have function that log 3 console.log . and my code only show the last console . how to show all ? Apr 4 at 10:10
11

Else, if you were concerned at keeping log, warn and error separate from one another, you could do something like this (adapted from MST's answer):

var log = document.querySelector('#log');

['log','warn','error'].forEach(function (verb) {
    console[verb] = (function (method, verb, log) {
        return function (text) {
            method(text);
            // handle distinguishing between methods any way you'd like
            var msg = document.createElement('code');
            msg.classList.add(verb);
            msg.textContent = verb + ': ' + text;
            log.appendChild(msg);
        };
    })(console[verb].bind(console), verb, log);
});

where #log is your HTML element. The variable verb is one of 'log', 'warn', or 'error'. You can then use CSS to style the text in a distinguishable way. Note that a lot of this code isn't compatible with old versions of IE.

3
  • 1
    Checked. Best console solution in this topic. Apr 25, 2016 at 12:42
  • 2
    This didn't capture any of the errors that were still sent to the Chrome Dev Tools output.
    – CaptainBli
    Jul 14, 2017 at 16:29
  • Perfect Answer. I tested in Codepen
    – aiffin
    Feb 15, 2018 at 12:09
7

How about something as simple as:

console.log = function(message) {$('#debugDiv').append('<p>' + message + '</p>');};
console.error = console.debug = console.info =  console.log
5
  • I voted your answer up. This is really smart. But it caused actual console stop working
    – Mohsen
    Jul 7, 2011 at 0:08
  • 10
    @DannyBeckett just editing with document.getElementById would be more constructive than trolling -1s on answers from 2011. Apr 8, 2013 at 17:32
  • 1
    this may send console message hardcoded in the JS, but it won't send the browser's own errors.
    – johny why
    May 23, 2020 at 10:57
  • 1
    @johnywhy - How do we access the browser's own errors? Dec 30, 2020 at 12:49
  • @AndrewPaul I wish i knew.
    – johny why
    Dec 31, 2020 at 16:27
0
<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <div id="logger" class="web_console"></div>

    <script type="text/javascript">

        // Overriding console object
        var console = {};

        // Getting div to insert logs
        var logger = document.getElementById("logger");

        // Adding log method from our console object
        console.log = function(text)
        {
            var element = document.createElement("div");
            var txt = document.createTextNode(text);

            element.appendChild(txt);
            logger.appendChild(element);
        }

        // testing
        console.log("Hello World...");
        console.log("WOW");

        /**
            console.log prints the message in the page instead browser console, useful to programming and debugging JS using a Android phone

        */
    </script>
</body>
</html>
0

I created a zero-dependency npm module for this case: console-events (surely if you're okay to use nodejs :P)

You can add event listener like that:

const { console } = require('console-events');

console.addEventListener('log', (e) => {
   e.preventDefault(); //if you need to prevent normal behaviour e.g. output to devtools console
   $('#debugDiv').append('<p>' + message + '</p>');
})
2
  • can you please add code snippet. how to add require in browser script? Nov 15, 2019 at 7:59
  • as well as it's an npm module, you can use webpack or gulp to bundle it to your javascript, so require will automatically put a module code into your output JS Nov 15, 2019 at 22:22
0

about console.log

✔️ variable number of arguments

console_log = console.log

console.log = (...a)=> {
  outDiv.innerHTML += a.join(' ') + '<br>'
}

❌ handle object representation

I thinks this is complex

JSON.stringify() can't handle all object.

❌ handle other behavior

'%s' '%c' things..

not impossible, but cumbersome


some related project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.