Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting stdout to file nodejs

Tags:

I've created:

var access = fs.createWriteStream('/var/log/node/api.access.log', { flags: 'w' }); 

Then piped:

process.stdout.pipe(access); 

Then tried:

console.log("test"); 

And nothing has appeared in /var/log/node/api.access.log. However this way is working:

process.stdout.pipe(access).write('test'); 

Could someone explain what am I doing wrong ?

like image 383
Supervision Avatar asked Sep 22 '15 14:09

Supervision


1 Answers

I solved this problem the following way:

var access = fs.createWriteStream('/var/log/node/api.access.log'); process.stdout.write = process.stderr.write = access.write.bind(access); 

Of course you can also separate stdout and stderr if you want.

I also would strongly recommend to handle uncaught exceptions:

process.on('uncaughtException', function(err) {   console.error((err && err.stack) ? err.stack : err); }); 

This will cover the following situations:

  • process.stdout.write
  • process.stderr.write
  • console.log
  • console.dir
  • console.error
  • someStream.pipe(process.stdout);
  • throw new Error('Crash');
  • throw 'never do this';
  • throw undefined;
like image 193
Anatol - user3173842 Avatar answered Oct 02 '22 15:10

Anatol - user3173842