How to safely wrap `console.log`?

后端 未结 10 499
日久生厌
日久生厌 2021-01-31 14:13

Suppose I want to include some calls to console.log for some legitimate production reason, say for something like a unit test harness. Obviously I would not want th

相关标签:
10条回答
  • 2021-01-31 15:12

    Paul Irish has a nice light wrapper/replacement for console.log().

    http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/

    Advantages:

    • Prevent errors if a console isn’t around (i.e. IE)
    • Maintains a history of logs, so you can look in the past if your console is added afterwards (e.g. firebug lite)
    • Light & simple.
    • Very quick to type -- log() or window.log().
    0 讨论(0)
  • 2021-01-31 15:15

    Try using the code snippet below... (this is my preferred approach because it makes you independent of window.console)

    var logger = (function (c) {
        "use strict";
        var m = {
            log: function (a, t) {
                if (!c) { return; /* return or call your custom function here */ }
                var l = c.log,
                    f = t === undefined ? l : (this.__dict__[t] || l);
                f.apply(c, a)
            },
            __dict__: {
                "trace": c.trace,
                "debug": c.debug,
                "info": c.info,
                "warn": c.warn,
                "error": c.error
            }
        };
    
        return {
            trace: function () { m.log(arguments, "trace"); },
            debug: function () { m.log(arguments, "debug"); },
            info: function () { m.log(arguments, "info"); },
            warn: function () { m.log(arguments, "warn"); },
            error: function () { m.log(arguments, "error"); },
            log: function () { m.log(arguments, undefined); }
        };
    }(window.console))
    

    So you may now try these in your code and see the result

    logger.info("Hello");
    logger.trace("Hello");
    logger.debug("Hello");
    logger.warn("Hello");
    logger.error("Hello");
    logger.log("Hello");
    
    0 讨论(0)
  • 2021-01-31 15:16

    As a slight variation on Chris' answer, simply define 'log' as a property of 'console' with an empty function:

    if (typeof console === "undefined") {
        console = {
            log: function () {
                return;
            } 
       };
    }
    
    0 讨论(0)
  • 2021-01-31 15:18

    Sorry, there was a bug in my post. Don't know how I missed it.

    The PROPER way to create a global console object, if it does not exist:

    if (typeof console === "undefined"){
        console={};
        console.log = function(){
            return;
        }
    }
    
    0 讨论(0)
提交回复
热议问题