Search code examples
javascriptexpresswinston

How to exclude cookies with express-winston?


Reading at express-winston README it seems quire easy to remove the headers from logged line: we can simply act on requestWhitelist option, but this will disable all the headers from being logged.

Is there a way to disable only the cookie header?


Solution

  • As far as i know, you can create a custom filter like:

    function customRequestFilter(req, propName) {
      if(propName !== "headers") return req[propName];
    
      const { cookie, ...rest } = req.headers;
    
      return rest;
    }
    

    And your winston options should be something like:

    expressWinston.logger({
        transports: [new winston.transports.Console()],
        // requestWhitelist: ['headers'],
        requestFilter: customRequestFilter,
        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
      })
    

    I hope this could help you! Cheers.