简体   繁体   中英

Customize/Decorate console.log under Node.js

I want to decorate the output of console.log under Node.js like following codes

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 = {
    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. Based my understanding, it will override the global.console , but it seems not. Why the global.console cannot be override?

The second question: Is there any better way to custom console.log?

Why the global.console cannot be override?

Because it is an accessor property with only a getter (which loads the console module ).
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.

Is there any better way to custom console.log ?

No, a console variable that is local to your module seems to be the best idea.

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.

As the others mentioned, it it not a very good idea to override the console.log function, because many modules depend on it.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM