Fluidbyte
Fluidbyte

Reputation: 5210

NodeJs Capture All process.stdout to File

I'm looking for a way to grab all process.stdout and pipe to a log file, I have the following:

import fs from 'fs';
let logFile = fs.createWriteStream('./test.log', {
  encoding: 'utf8',
  flags   : 'a'
});
process.stdout.pipe(logFile);

However, it seems to still spit all stdout to the console and I'm not getting anything in the log file (although it's being created).

Upvotes: 2

Views: 4395

Answers (2)

Adrian Schneider
Adrian Schneider

Reputation: 7449

I'd rather have the program only write to stdout and have the process that calls node decide what to do with the output:

node server | tee test.log

This has a few benefits:

  • Doesn't couple your code to your logging infrastructure
  • Doesn't lock the file while you are writing logs (for instance, you'd need to restart your process whenever you wanted to rotate your logs -- bad for servers)

And avoids a very serious drawback:

  • You don't have to monkeypatch any core node stuff which may have serious side effects somewhere else in your application (or conflicts with another library doing the same thing)

Upvotes: 4

Jeremy Pridemore
Jeremy Pridemore

Reputation: 1995

I think this isn't working because process.stdout is a write stream that can't be piped from, though I'm not completely sure. What I did get working was the following example, where I override stdout with a new writable stream that has a _write method that calls forward to the file stream's write:

var fs = require('fs');
var writeStream = fs.createWriteStream('./test.log', {
  encoding: 'utf8',
  flags: 'w'
});

process.stdout = require('stream').Writable();
process.stdout._write = function(chunk, encoding, callback) {
    writeStream.write(chunk, encoding, callback);
};

console.log('test from console.log');

Upvotes: 0

Related Questions