Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
faizanEnbd opened this issue Dec 24, 2024 · 1 comment
Labels
type: question Questions about the usage of the library.

Comments

@faizanEnbd
Copy link

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.

@faizanEnbd faizanEnbd added the type: question Questions about the usage of the library. label Dec 24, 2024
@wbusby88
Copy link

wbusby88 commented Mar 3, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question Questions about the usage of the library.
Development

No branches or pull requests

2 participants