1

I want how to log both to file and console. This is my code snippet:

I want to make it possible to both record to console and record to file. The code below works, but is there any way to do what I just mentioned?

var fs = require("fs");
var Logger = (exports.Logger = {});
var infoStream = fs.createWriteStream("logs/info.txt");
var errorStream = fs.createWriteStream("logs/error.txt");
var debugStream = fs.createWriteStream("logs/debug.txt");

Logger.info = function(msg) {
  var message = new Date().toISOString() + " : " + msg + "\n";
  infoStream.write(message);
};

Logger.debug = function(msg) {
  var message = new Date().toISOString() + " : " + msg + "\n";
  debugStream.write(message);
};

Logger.error = function(msg) {
  var message = new Date().toISOString() + " : " + msg + "\n";
  errorStream.write(message);
};

1 Answer 1

1

I would use winston.

You can create different transports with different options.

export const Logger = winston.createLogger({
  transports: [
    new winston.transports.Console({ silent: process.env.NODE_ENV == "test" }),
    new winston.transports.File({ filename: "log/error.log" }),
  ],
})

For instance if you create a transport for debug/info/error and combine it with silent option so only the wanted files go to the log, there is also a level configuration key, but it will filter out the errors below that level.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.