6

I am trying to kill a process at first, I executed with

exec  = require('child_process').exec;
exec('kill xxx', function(error, stdout, stderr) {
    if (error) {
        console.log('exec error: ', error);
    }else{
       console.log(stdout)
    }
});

I noticed the kill program probably started a child process, whose output cannot be captured here as stdout.

So can I generally capture these console output which seem to be not very relevant with the code?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
J.R.
  • 769
  • 2
  • 10
  • 25
  • 4
    Possible duplicate of [Node: log in a file instead of the console](https://stackoverflow.com/questions/8393636/node-log-in-a-file-instead-of-the-console) – Seth McClaine Dec 05 '17 at 16:36
  • If you want to truly "catch them all" you may output everything to a file with "npm run dev > log.txt" and then create an external app/script to process the dumped text to a dashboard or redirect the text to a remote logger – Heroselohim Mar 30 '23 at 02:07

1 Answers1

8

Stolen: Node: log in a file instead of the console

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

ANSWER #2 This message is not created by console.log rather just the Linux system itself. How to catch this?

I think you should be able to do something with fs like so...

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

const command = 'node your_node_script'; //Whatever you would run in terminal

cp.exec(command, (error, stdout, stderr) => {
    if(error) {
        log_file.write(error);

    }
    if(stdout) {
        log_file.write(stdout);
    }
    if(stderr) {
        log_file.write(stderr);
    }
});
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
  • hmm, the problem is. The console output is not necessary created by console.log. E.g. when I killed a process, wait for 2 s, then the console will generate a message "xxx terminated". This message is not created by console.log rather just the Linux system itself. How to catch this? – J.R. Dec 06 '17 at 08:20
  • Updated answer with a suggestion to try. – Seth McClaine Dec 06 '17 at 17:08
  • it's partiatly works, but doesn't show second argument fro console.log with varibale, only text data quoted – Angelzzz Oct 12 '18 at 12:34