Piping Morgan into Winston causes weird characters

351 views Asked by At

Following this post: Node.js - logging / Use morgan and winston

I setup the logger as follows;

const winston = require('winston');
const datadogWinston = require('datadog-winston');
const os = require('os');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({filename: 'test.log'}),
    new datadogWinston({
      apiKey: process.env.DATADOG_APIKEY,
      hostname: os.hostname(),
      service: 'korabo',
      ddsource: 'nodejs',
    }),
  ],
});

logger.stream = {
  write: (message, _encoding) => {
    logger.info(message);
  },
};

module.exports = logger;

However, whenever winston logs an item, it ends up looking like this;

info: [0mGET /stylesheets/style.css [36m304[0m 1.550 ms - -[0m

Morgan instance;

const logger = require('./lib/logger');

const app = express();

...

app.use(morgan('dev', {stream: logger.stream}));

How can I fix those strange characters from appearing in the logs?

1

There are 1 answers

0
SeChan Park On

you can remove all ANSI colors/styles from message : Remove all ANSI colors/styles from strings

logger.stream = {
  write: (message, _encoding) => {
    logger.http(
      message.replace(
        /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
        ""
      )
    );
  },
};