Overriding console.log in Node.js, and other thoughts about logging in Node apps

By: (plus.google.com) +David Herron; Date: 2012-08-06 22:57

Tags: Node.JS »»»» Logging

How should Node.js programs best do logging?  When that question came up in the (groups.google.com) 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  (ditesh.gathani.org) 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  (github.com) 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: (www.quora.com) http://www.quora.com/What-is-the-standard-idiom-for-rebinding-console-log-with-stderr-in-node-js

The console-trace module ( (github.com) https://github.com/LearnBoost/console-trace) implements another method of overriding console.log. This is the core piece of code ( (github.com) https://github.com/LearnBoost/console-trace/blob/master/console-trace.js):