typestack/routing-controllers

question: How to capture api response body for logging purpose in @Middleware({type: 'after'})

Opened this issue · 1 comments

Hi Everyone,

I have tried different ways to capture logs in @Middleware({type: 'after'}) but I was not able to access the response body which is being sent from the api response.

It tried with res.on('finish'), global middleware in app.ts file. but still I am not able to capture the api response body.

Can anyone help me with this issue, what I am missing here.

Thanks in advance.

This example worked for me:

import { Middleware, ExpressMiddlewareInterface } from "routing-controllers";
import { Request, Response, NextFunction } from "express";
import { Service } from "typedi";

@Service()
@Middleware({ type: "before" })
export class ResponseLoggerMiddleware implements ExpressMiddlewareInterface {
  use(req: Request, res: Response, next: NextFunction): void {
    const originalSend = res.send.bind(res);
    let responseBody: any;

    res.send = (body?: any): Response => {
      responseBody = body;
      return originalSend(body);
    };

    res.on("finish", () => {
      const status = res.statusCode;
      const logType = status >= 400 ? "ERROR" : "OK";
      console.log(
        `[${new Date().toISOString()}] ${req.method} ${req.url} - Status: ${status} (${logType}) - Response Body:`,
        responseBody,
      );
    });

    next();
  }
}

Add this to your global middlewares wherever you initialise the server