How to configure Node.js to log to a file instead of the console?

How to configure Node.js to log to a file instead of the console?

I want to redirect the console.log output to a file rather than displaying it in the console. How can I achieve this in Node.js while ensuring all logs are properly written to a file?

Override console.log Using fs

You can override console.log to log directly to a file by using fs.appendFile:

const fs = require('fs');
const logFile = 'app.log';

console.log = function(message) {
  fs.appendFile(logFile, message + '\n', (err) => {
    if (err) throw err;
  });
};

// Test the new logging console.log("This is a log message");

This will append logs to app.log.

Winston is a popular Node.js logging library that can be configured to log to a file.

First, install it via npm:

npm install winston

Then, configure Winston to log messages to a file:

const winston = require('winston');

const logger = winston.createLogger({
  transports: [
    new winston.transports.File({ filename: 'app.log' })
  ]
});

logger.info('This is a log message');

Winston provides advanced features such as log levels, file rotation, and more.

Redirect process.stdout to a File

You can redirect the standard output (stdout) to a file by using

fs.createWriteStream:

const fs = require('fs');
const logFile = fs.createWriteStream('app.log', { flags: 'a' });
process.stdout.write = logFile.write.bind(logFile);

// Now all console.log() calls will be written to the log file console.log("This is a log message");

This method overrides the default stdout stream to write logs to app.log.