bithavoc / express-winston

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

I need to capture both error log object and access log object and send it using slack bot #254

Closed sujeet-agrahari closed 3 years ago

sujeet-agrahari commented 3 years ago

Mentioned transports are http, console and file.

Is there a way I could capture generated log object before it is written to file or streamed to console?

I could then easily send it.

 var router = require('./my-express-router');

    app.use(expressWinston.logger({
      transports: [
        new winston.transports.Console()
      ],
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.json()
      ),
      meta: true, // optional: control whether you want to log the meta data about the request (default to true)
      msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
      expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
      colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
      ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response
    }));

    app.use(router); // notice how the router goes after the logger.

I need to capture the request log object, is it possible?

sujeet-agrahari commented 3 years ago

I did it with a custom Transport.

const Transport = require('winston-transport');
const { sendToSlackChannel } = require('../slack-bot');

module.exports = class SlackBotTransport extends Transport {
  constructor(opts) {
    super(opts);
  }

  log(info, callback) {
    sendToSlackChannel({ data: info });
    // Perform the writing to the remote service
    callback();
  }
};