Node: log in a file instead of the console


Can I configure console.log so that the logs are written on a file instead of being printed in the console?

12/5/2011 11:58:37 PM

Accepted Answer

Update 2013 - This was written around Node v0.2 and v0.4; There are much better utilites now around logging. I highly recommend Winston

Update Late 2013 - We still use winston, but now with a logger library to wrap the functionality around logging of custom objects and formatting. Here is a sample of our logger.js

Should be as simple as this.

var access = fs.createWriteStream(dir + '/node.access.log', { flags: 'a' })
      , error = fs.createWriteStream(dir + '/node.error.log', { flags: 'a' });

// redirect stdout / stderr
11/7/2013 1:56:57 PM

You could also just overload the default console.log function:

var fs = require('fs');
var util = require('util');
var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags : 'w'});
var log_stdout = process.stdout;

console.log = function(d) { //
  log_file.write(util.format(d) + '\n');
  log_stdout.write(util.format(d) + '\n');

Above example will log to debug.log and stdout.

Edit: See multiparameter version by Clément also on this page.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow