1

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?

2
  • I think you have to define it explicitly as: global.console = .., not console = .. Commented Nov 3, 2015 at 11:02
  • 1. Use util.log if you want a better log. 2. the way you Are taking arguments is bad for what you want, you can only log 1 argument now, while console.log takes as many as specified. Commented Nov 3, 2015 at 11:05

2 Answers 2

2

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, e.g. 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.