简体   繁体   中英

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).

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)

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM