Bootstrap FreeKB - Node.js - Logging a Log Files
Node.js - Logging a Log Files

Updated:   |  Node.js articles

Let's say you have a file named app.js that contains the following console.log.

console.log("Hello World");

 

If you use the node CLI to run app.js, "Hello World" should be displayed as stdout on your console and will not be written to a log file.

~]$ node app.js
Hello World

 

By far, the easiest way to append the console.log events to a log file is to use plain ole redirection.

~]$ node app.js >> app.log 2>&1
Hello World

 

Or, here is how you can create your own logger. In this example, there will be no output on the console and instead the stdout and stderr will be appended to log file.

const fs = require('fs')
const stdout_log = fs.createWriteStream('stdout.log');
const stderr_log = fs.createWriteStream('stderr.log');
const logger = new console.Console(stdout_log, stderr_log);

logger.log('Hello World');

 

Better yet, use the Winston Logger.

const { createLogger, format, transports } = require('winston');

const logger = createLogger({
  format: format.simple(),
  transports: [
    new transports.Console(),
    new transports.File({ filename: 'all.log' }),
  ],
});

logger.error("my error message");
logger.warn("my warning message");
logger.info("my info message");

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 66ee4a in the box below so that we can be sure you are a human.