Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting output to a log file using node.js

Tags:

node.js

I have a child process that I am using as follows in node.js. Instead of redirecting the output to the console I would like to put the output in a log file located somewhere on the machine this is running on (and should work for both windows and mac).

The code below is what I am using and I would like to output the files into a log file. What changes needed to do that here? Thanks!

My Code:

var spawn = require('child_process').spawn,     ls    = spawn('ls', ['-lh', '/usr']);  ls.stdout.on('data', function (data) {   console.log('stdout: ' + data); });  ls.stderr.on('data', function (data) {   console.log('stderr: ' + data); });  ls.on('close', function (code) {   console.log('child process exited with code ' + code); }); 
like image 899
user220755 Avatar asked Apr 22 '13 20:04

user220755


2 Answers

Here's an example of logging to file using streams.

var logStream = fs.createWriteStream('./logFile.log', {flags: 'a'});  var spawn = require('child_process').spawn,     ls    = spawn('ls', ['-lh', '/usr']);  ls.stdout.pipe(logStream); ls.stderr.pipe(logStream);  ls.on('close', function (code) {   console.log('child process exited with code ' + code); }); 
like image 174
generalhenry Avatar answered Sep 16 '22 21:09

generalhenry


There are two ways you can achieve this, one is using

let logConsoleStream = fs.createWriteStream('./logConsoleFile.log', {flags: 'a'}); let logErrorStream = fs.createWriteStream('./logErrorFile.log', {flags: 'a'}); 

and redirect all logs or errors using this

ls.stdout.pipe(logConsoleStream );  // redirect stdout/logs only ls.stderr.pipe(logErrorStream );    // redirect error logs only 

by separating log files you will have separate files for Error logs and console logs this is exactly same as generalhenry shared above

And Second Way for Achieving this with the help of Command Line

when you execute node app from the command line

node app/src/index.js 

you can specify here where you want to redirect logs and Errors from this application

there are three stream redirection commands using the command line

`>`     It will redirect your only stdout or logs to the specified path `2>`    It will redirect your errors logs to the specified path `2>&1 ` It will redirect all your stdout and stderr to a single file 

example: how you will use these commands

node app/src/index.js > ./logsOnly.txt node app/src/index.js 2> ./ErrorsOnly.txt node app/src/index.js 2>&1 ./consoleLogsAndErrors.txt 

I hope someone coming later finds this helpful

if there is I done wrong way please do let me know it will help me and others Thanks

like image 39
Hanzla Habib Avatar answered Sep 20 '22 21:09

Hanzla Habib