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

; Date: Mon Aug 06 2012

Tags: Node.JS »»»» Logging

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  (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):

About the Author(s)

(davidherron.com) David Herron : David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.

Books by David Herron

(Sponsored)