bithavoc / express-winston

express.js middleware for winstonjs
https://www.npmjs.com/package/express-winston
MIT License
796 stars 187 forks source link

[Feature] Expected response time colors #219

Open ruscon opened 4 years ago

ruscon commented 4 years ago

Expected response time colors feature

One of the options that come to mind: An anonymous function that should return one of the log levels string name https://github.com/winstonjs/winston#logging-levels

"responseTimeColors": (responseTimeMs: number) => {
    switch(responseTimeMs) {
        case responseTimeMs < 50:
            return 'debug';
        case responseTimeMs < 100:
            return 'info';
        case responseTimeMs < 200:
            return 'warn';
        default:
            return 'red';
    }
}

Or try using the more interesting options described here (in the end of thee section) https://github.com/winstonjs/winston#using-custom-logging-levels

Additionally, you can also change background color and font style. For example,

baz: 'italic yellow',
foobar: 'bold red cyanBG'
yinzara commented 4 years ago

Technically this can be done without a modification to the express-winston library currently.

You would first need to create a winston instance in which you've defined custom log levels with matching colors with the "colorize" formatter then use the "level" option of express-winston to define a custom level function that uses the res.

import winston from "winston";
import * as expressWinston from "express-winston";

const customLevels = {
  levels: {
    slow: 0,
    medium: 3,
    fast: 3
  },
  colors: {
    slow: 'bold red',
    medium: 'yellow',
    fast: 'green'
  }
};

const format = winston.format.combine(
  winston.format.colorize(),
  winston.format.json()
);

const logger = winston.createLogger({ 
  levels: customLevels.levels,
  format
});
winston.addColors(customLevels.colors);

const expressLogger = expressWinston.logger({
   winstonInstance: logger,
   level: (req, res) => {
       if (res.responseTime > 3000) {
           return "slow";
       } else if (res.responseTime > 1000) {
           return "medium";
       } else {
           return "fast";
       }
   }
});