logger.middleware.ts 505 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { Request, Response, NextFunction } from 'express';
  2. /**
  3. * 请求日志中间件
  4. */
  5. export const loggerMiddleware = (
  6. req: Request,
  7. res: Response,
  8. next: NextFunction
  9. ): void => {
  10. const start = Date.now();
  11. res.on('finish', () => {
  12. const duration = Date.now() - start;
  13. const { method, originalUrl, ip } = req;
  14. const { statusCode } = res;
  15. console.log(
  16. `${method} ${originalUrl} ${statusCode} ${duration}ms - ${ip}`
  17. );
  18. });
  19. next();
  20. };