Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Alter console.log

0.00/5 (No votes)
31 Oct 2013 1  
Adding stuff to your logs.

Introduction

If you need to alter Node.JS server or JavaScript client console.log function w/o the vsprintf library, dynamically build the util.format command and execute with JavaScript eval().

Using the Code

Place the following code in your file to replace the default console.log function:

util = require('util');
console.log = function(a) {
    if (arguments.length>1) {
        var cmd = 'util.format(';
        for (i in arguments) {
            if (i>0)
                cmd += ',';
            cmd += 'arguments['+i+']';
        }
        cmd += ')';
        util.log(eval(cmd));
    }
    else
        util.log(a);
};

This is much better:

util = require('util');
console.log = function() {
    process.stdout.write((new Date()).toISOString().substring(0,19).replace('T', ' ')+': ');
    process.stdout.write(util.format.apply(this, arguments) + '\n');
};

History

  • September 15, 2013 - First version.
  • October 31, 2013 - Found a better way to do the same thing. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here