Logging Morgan HTTP Events Using Winston in Express App Has Issues with Colorize

61 views Asked by At

I am creating a Node.js/Express.js server and I want to implement some logging using Winston. I had Morgan set up already to log to the console, and I decided to implement code to log the Morgan events to the same log file that Winston is now logging to. Here is how I am doing this:

const winston = require("winston");
const db = require("config").get("db");
require("winston-mongodb");
require("express-async-errors");

const logFormat_file = winston.format.combine(
  winston.format.timestamp({
    format: "YYYY-MM-DD HH:mm:ssZZ",
  }),
  winston.format.printf(
    (info) =>
      `${info.timestamp} ${info.level}: ${info.message}` +
      (info.splat !== undefined ? `${info.splat}` : " ")
  ),
  // UNCOMMENTING THE FOLLOWING FIXES THE STRANGE BEHAVIOR
  // winston.format.uncolorize({ message: true }) 
);

module.exports = function (app) {
  winston.exceptions.handle(
    new winston.transports.Console({ colorize: true, prettyPrint: true }),
    new winston.transports.File({
      filename: "uncaughtExceptions.log",
    })
  );

  process.on("unhandledRejection", (ex) => {
    throw ex;
  });

  winston.add(
    new winston.transports.File({
      filename: "logfile.log",
      format: logFormat_file,
    })
  );
  winston.add(
    new winston.transports.MongoDB({
      db: db,
      level: "info",
      options: { useUnifiedTopology: true },
    })
  );
  // ADD STREAM FOR MORGAN LOGGER
  app.use(
    require("morgan")("dev", {
      stream: {
        write: function (message, encoding) {
          // 'replace' removes the newline character added by Morgan
          winston.info(message.replace(/\n$/, ""));
        },
      },
    })
  );
};

As you can see, this logs to both logfile.log and a mongoDB collection. In both of these places, the events that Morgan logs look like the following:

2023-11-26 20:29:49-0600 info: [0mPOST /walk-ins/create-new-order [31m500 [0m5.706 ms - 119[0m 

Each log entered by Morgan includes a special character followed by [0m or something similar. I suspected that this had something to do with the colorize, and after seeing this post I realize that this is special formatting for the command line.

The default Morgan logs look great on the command line, and I was wondering if there was a way to preserve that formatting in the logfile. Or is it possible that it is just the way that VSCode is displaying it and if I changed some settings it would appear properly? If so I would not be concerned about these strange characters in the logfile.

One work around I am currently using is to uncolorize info messages (as shown commented out in the snippet above), but I'd prefer a solution that preserves the colors that Morgan provides.

There are a lot of StackOverflow posts about this formatting, but I have not found one addressing how to fix it in the context of Morgan/Winston.

0

There are 0 answers