How to safely wrap `console.log`?

后端 未结 10 527
日久生厌
日久生厌 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: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");
    

提交回复
热议问题