[英]Customize/Decorate console.log under Node.js
I want to decorate the output of console.log
under Node.js
like following codes 我想像下面的代码一样装饰
Node.js
下console.log
的输出
var console = {
log: function(text) {
global.console.log('Test: ' + text);
}
};
console.log('custom console is here');
Output: 输出:
Test: custom console is here
However, if I remove the var
before the variable console
, 但是,如果我在变量
console
之前删除var
,
console = {
log: function(text) {
global.console.log('Test: ' + text);
}
};
console.log('custom console is here');
The output will be 输出将是
custom console is here
I know the console
will become the global variable when the var
is deleted. 我知道删除
var
, console
将成为全局变量。 Based my understanding, it will override the global.console
, but it seems not. 根据我的理解,它将覆盖
global.console
,但似乎没有。 Why the global.console
cannot be override? 为什么无法覆盖
global.console
?
The second question: Is there any better way to custom console.log? 第二个问题: 是否有更好的自定义console.log方法?
Why the
global.console
cannot be override?为什么无法覆盖
global.console
?
Because it is an accessor property with only a getter (which loads the console
module ). 因为它是只有getter的访问器属性(将加载
console
模块 )。
Try strict mode and your assignment will throw. 尝试严格模式,您的作业将会抛出。
It can be overridden by using Object.defineProperty
, but that's a very bad idea, as many modules depend on it. 可以使用
Object.defineProperty
重写它,但这是一个非常糟糕的主意,因为很多模块都依赖它。
Is there any better way to custom
console.log
?有什么更好的方法来定制
console.log
吗?
No, a console
variable that is local to your module seems to be the best idea. 不,对于您的模块而言,本地的
console
变量似乎是最好的主意。
Of course you can improve your implementation, eg to deal with multiple arguments correctly, to be an actual Console
instance (with all methods), or to be available via require("my-console.js")
so that you can use it in multiple modules. 当然,您可以改进实现,例如正确处理多个参数,成为实际的
Console
实例(具有所有方法)或通过require("my-console.js")
可用,以便可以在其中使用多个模块。
As the others mentioned, it it not a very good idea to override the console.log
function, because many modules depend on it. 正如其他人提到的那样,重写
console.log
函数不是一个好主意,因为许多模块都依赖它。
Besides this, in your code you set the console variable to a completely new object with only the function log
and this function can only handle 1 argument, while console.log
can handle multiple arguments. 除此之外,您还可以在代码中将console变量设置为一个只有函数
log
全新对象,并且该函数只能处理1个参数,而console.log
可以处理多个参数。
If you really want to override the function, try something like this instead: 如果您确实想覆盖该功能,请尝试以下类似方法:
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
But if you just need a better debug log, try the debug package. 但是,如果您只需要更好的调试日志,请尝试使用调试包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.