dougmoscrop / serverless-http

Use your existing middleware framework (e.g. Express, Koa) in AWS Lambda 🎉
Other
1.72k stars 165 forks source link

Is there a way to leverage close/finish events on http.ServerResponse? #197

Closed timmystephani closed 3 years ago

timmystephani commented 3 years ago

Hi there - first, thanks for all your work.

My question is if there is a way to add some logic that leverages the close event of the response (docs). My use case is logging a summary of the request/response like so:

import { Request, Response, NextFunction} from 'express';
import { logger } from '../utils/logger';

export const serviceLogMiddleware = (req: Request, res: Response, next: NextFunction): void => {
  // See https://nodejs.org/api/http.html#http_event_close_1
  res.on('close', () => {
    logger.log({
      level: 'info',
      req: {
        method: req.method,
        originalUrl: req.originalUrl,
        url: req.url
      },
      res: {
        statusCode: res.statusCode
      }
    });
  });
  next();
};

It seems as soon as the response is returned that the server code stops executing and no logs are emitting (though they do when running the express app locally). Is this just an inherent limitation of running Express on Lambda? If so, any suggestions for being able to log a "summary" of the request/response?

Thanks!

timmystephani commented 3 years ago

After browsing through the source code a little (notably finish.js), I noticed you did have support for a few events (error, end, and finish). I switched to using finish and that did work as expected.