How should Node.js programs best do logging? When that question came up in the node users mailing list, Tim Caswell answered to just use console.log, and if you want to send the log to somewhere other than stdout then to override the function. That makes the Java programmer recoil with "eeew, overriding a system function is wrong" but hey we're in a JavaScript environment. This sort of thing is par for the course in JavaScript. So, how do you go about doing this?
The first interesting thing I found looking for wasn't an answer to this question, but instead an interesting behavior of console.log
. If the object being logged has a .inspect
function, console.log
uses that inspect
function to get the string to be logged. See
http://ditesh.gathani.org/blog/2011/07/console-log-ing-objects/
An interesting answer is on Quora, and there is an NPM module to implement the answer (see https://github.com/jonseymour/node-idiomatic-stdio). The answer is:
console.log=(function() {
var orig=console.log;
return function() {
try {
var tmp=process.stdout;
process.stdout=process.stderr;
orig.apply(console, arguments);
} finally {
process.stdout=tmp;
}
};
})();
console.info=(function() {
var orig=console.info;
return function() {
try {
var tmp=process.stdout;
process.stdout=process.stderr;
orig.apply(console, arguments);
} finally {
process.stdout=tmp;
}
};
})();
Source: http://www.quora.com/What-is-the-standard-idiom-for-rebinding-console-log-with-stderr-in-node-js
The console-trace module (
https://github.com/LearnBoost/console-trace) implements another method of overriding console.log
. This is the core piece of code (
https://github.com/LearnBoost/console-trace/blob/master/console-trace.js):