在Node.js下自定义/装饰console.log
Customize/Decorate console.log under Node.js
我想在Node.js
下装饰console.log
的输出,就像下面的代码一样
var console = {
log: function(text) {
global.console.log('Test: ' + text);
}
};
console.log('custom console is here');
输出:
Test: custom console is here
但是,如果我删除变量console
之前的var
,
console = {
log: function(text) {
global.console.log('Test: ' + text);
}
};
console.log('custom console is here');
输出将是
custom console is here
我知道当var
被删除时,console
将成为全局变量。根据我的理解,它将覆盖global.console
,但似乎不是为什么global.console
不能被覆盖
第二个问题:有没有更好的方法来自定义console.log
为什么
global.console
不能被覆盖?
因为它是一个只有getter(用于加载console
模块)的访问器属性
尝试严格模式,你的作业就会失败。
它可以通过使用Object.defineProperty
覆盖,但这是一个非常糟糕的主意,因为许多模块都依赖于它
有没有更好的方法来定制
console.log
?
不,最好使用模块本地的console
变量。
当然,您可以改进您的实现,例如,正确处理多个参数,成为一个实际的Console
实例(使用所有方法),或者通过require("my-console.js")
可用,以便您可以在多个模块中使用它。
正如其他人所提到的,覆盖console.log
函数不是一个好主意,因为许多模块都依赖于它
除此之外,在您的代码中,您将控制台变量设置为一个全新的对象,该对象只有函数log
,该函数只能处理一个参数,而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
但是,如果您只是需要更好的调试日志,请尝试调试包。
相关文章:
- Array.length似乎不起作用;console.log则显示其他情况
- 有没有一种方法可以在控制台关闭的情况下让console.log()在IE中记录消息
- console.log以外的Javascript输出函数
- Console.debug在ie10中不工作
- 如果在代码末尾进行求值,jQuery-console.log将提供空数组
- 为什么生成器中的console.log会按这样的顺序出现
- 没有装饰的小型浏览器框架
- async问题,JS Promise无法返回结果,但可以使用console.log
- 谷歌地图:函数返回未定义的值在console.log中运行良好
- 我应该返回一个类似console.log()的方法调用吗
- console.log无法运行Mac OS X
- 如何使console.log可配置
- 如何使用console.log语句在Mocha中测试函数
- 为什么我可以't直接将console.log()设置为回调函数
- Node.js/Express未输出console.log,highcharts.js给出未定义的错误
- console.log在角度控制器内不工作
- Mocking console.log()/MOCHA测试框架中的任何其他函数
- 如何使用console.log在因果报应测试中检查函数
- 装饰$errorProvider时的循环引用
- 在Node.js下自定义/装饰console.log