在Node.js下自定义/装饰console.log

时间:2015-11-03 10:56:52

标签: javascript node.js console.log

我想在console.log下装饰Node.js的输出,如下面的代码

var console = {
    log: function(text) {
         global.console.log('Test: ' + text);
    }
};

console.log('custom console is here');

输出:

Test: custom console is here

但是,如果我在变量var之前删除console

console = {
    log: function(text) {
         global.console.log('Test: ' + text);
    }
};

console.log('custom console is here');

输出

custom console is here

我知道删除consolevar将成为全局变量。根据我的理解,它将覆盖global.console,但似乎没有。 为什么global.console无法覆盖?

第二个问题:有没有更好的方法来自定义console.log?

2 个答案:

答案 0 :(得分:1)

  

为什么global.console无法覆盖?

因为它是only a getter的加载器属性(加载console module) 尝试严格模式,你的任务就会抛出。

可以使用Object.defineProperty覆盖它,但这是一个非常糟糕的主意,因为许多模块都依赖它。

  

有没有更好的方法来自定义console.log

不,您模块本地的console变量似乎是最好的主意。

当然,您可以改进实施,例如:正确处理多个参数,成为一个实际的Console实例(包含所有方法),或通过require("my-console.js")提供,以便您可以在多个模块中使用它。

答案 1 :(得分:1)

正如其他人提到的那样,覆盖console.log函数并不是一个好主意,因为很多模块都依赖它。

除此之外,在您的代码中,您将控制台变量设置为仅具有函数log的全新对象,并且此函数只能处理1个参数,而console.log可以处理多个参数。

如果您真的想要覆盖该功能,请尝试这样的事情:

function decorateLog(string) {
    var originalFunc = console.log;
    console.log = function(){
      originalFunc.apply(console, [string].concat([].slice.call(arguments)))
    }
}

decorateLog('Test:')

console.log('custom console is here'); //=> Test: custom console is here
console.log('foo', 'bar'); //=> Test: foo bar

但如果您只需要更好的调试日志,请尝试debug包。