bithavoc / express-winston

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

Feature Request: Can colorize support arbitrary msg (instead of just expressFormat) #121

Closed jiinjoo closed 7 years ago

jiinjoo commented 7 years ago

With reference to

            var expressMsgFormat = "{{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms";
            if (options.colorize) {
              // Palette from https://github.com/expressjs/morgan/blob/master/index.js#L205
              var statusColor = 'green';
              if (res.statusCode >= 500) statusColor = 'red';
              else if (res.statusCode >= 400) statusColor = 'yellow';
              else if (res.statusCode >= 300) statusColor = 'cyan';

              expressMsgFormat = chalk.grey("{{req.method}} {{req.url}}") +
                " " + chalk[statusColor]("{{res.statusCode}}") + " " +
                chalk.grey("{{res.responseTime}}ms");
            }
            var msgFormat = !options.expressFormat ? options.msg : expressMsgFormat;

I would like to pass in options.msg that contains {{res.statusCode}} but would like it coloured the same as above.

I couldn't work around it with my own middleware because options.msg is set during config and not dynamically at res.end.

Something like

            var expressMsgFormat = "{{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms";
            var customMsgFormat = options.msg;
            if (options.colorize) {
              // Palette from https://github.com/expressjs/morgan/blob/master/index.js#L205
              var statusColor = 'green';
              if (res.statusCode >= 500) statusColor = 'red';
              else if (res.statusCode >= 400) statusColor = 'yellow';
              else if (res.statusCode >= 300) statusColor = 'cyan';

              if (options.expressFormat) {
                expressMsgFormat = chalk.grey("{{req.method}} {{req.url}}") +
                  " " + chalk[statusColor]("{{res.statusCode}}") + " " +
                  chalk.grey("{{res.responseTime}}ms");
              } else {
                customMsgFormat = customMsgFormat.replace("{{res.statusCode}}",
                  chalk[statusColor]("{{res.statusCode}}"))
              }
            }
            var msgFormat = !options.expressFormat ? customMsgFormat : expressMsgFormat;

with probably better checking for extra space, pre-chalking etc. Does this break any user expectation?

rosston commented 7 years ago

Yes, this is totally doable! In fact, the module used to do this until I accidentally broke it in 2.0.0 (https://github.com/bithavoc/express-winston/commit/e79a213d). I'll add a fix + test for it soon.

rosston commented 7 years ago

Fix is published in 2.1.0.