Intercept Console Messages in Javascript



Published: 2019-10-13 12:04:00 +0000
Categories: Javascript,

Language

Javascript

Description

Sometimes you want to intercept messages sent to console with console.log(), console.warn() etc. This might be so that you can use the messages in a JS originated error report form, or otherwise need to make the messages available to users without needing to explain about developer tools to them

This short snippet will collect messages in an array window.logs so that you can then access the messages from other javascript functions

Certain forms of message will not be caught however. For example CORS errors, whilst visible in the console, are deliberately not made available in the DOM by the browser for security reasons.

Snippet

window.logs = [];
(function(){
    var oldLog = console.log;
    var oldWarn = console.warn;
    var oldInfo = console.info;
    var oldError = console.error;
    var oldClear = console.clear

    console.log = function (message) {
        window.logs.push(['log:',arguments]);
        oldLog.apply(console, arguments);
    };

    console.warn = function (message) {
        window.logs.push(['warn:',arguments]);
        oldWarn.apply(console, arguments);
    };

    console.info = function (message) {
        window.logs.push(['info:',arguments]);
        oldInfo.apply(console, arguments);
    };

    console.error = function (message) {
        window.logs.push(['error:',arguments]);
        oldError.apply(console, arguments);
    };

    console.clear = function () {
       window.logs = [];
       oldClear();
    };

})();

Usage Example

// Push some messages to the console after the snippet has been applied
console.log("We're going on a bear hunt");
console.warn("I don't like the look of this");
console.error("Don't panic! Don't Panic!");

// Create a pre in the page (means you can just paste this example into dev tools)
pr = document.createElement('pre');
pr.id="logcontainer";
document.body.appendChild(pr);

// Write the messages into our pre
cont = document.getElementById('logcontainer');
for (var i=0; i<window.logs.length; i++){

    // Extract strings only (some JS functions push objects to console)
    keys = Object.keys(window.logs[i][1]);
    msgs = []
    for (var a=0;a<keys.length;a++){
        if (typeof(window.logs[i][1][a]) == "string"){
            msgs.push([ window.logs[i][0],
                        window.logs[i][1][a],
                        "\n"].join(" ")
                     );
        }
    }
    msgstr = msgs.join(" ");

    // Append the string
    cont.appendChild(document.createTextNode(msgstr));
}

// Flush the console
console.clear()

Keywords

js, javascript, console, messages, intercept, catch, log,

Latest Posts


Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, yr4pnhounvdybotb.onion and snippets.6zdgh5a5e6zpchdz.onion