Redirecting output to a log file using node.js

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

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

Tags:

Node.Js