Skip to content

Commit

Permalink
feat: adding response body to the access log (#5)
Browse files Browse the repository at this point in the history
* feat: adding response body to the access log

* chore: adding error handling
  • Loading branch information
artursudnik authored Oct 17, 2023
1 parent 7067bc9 commit fcbee66
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions apps/vc-api/src/middlewares/http-logger.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,45 @@ export class HttpLoggerMiddleware implements NestMiddleware {

let finished = false;

let responseBody: string;

try {
const oldWrite = res.write;
const oldEnd = res.end;
const chunks: Buffer[] = [];

res.write = (...args: unknown[]): boolean => {
try {
chunks.push(args[0] as Buffer);
} catch (err) {
this.logger.error(`error collecting response body chunk: ${err}`);
this.logger.verbose(err.stack);
}

return oldWrite.apply(res, args);
};

res.end = (...args: unknown[]) => {
try {
const chunk = args[0] as Buffer;

if (chunk) {
chunks.push(chunk);
}

responseBody = Buffer.concat(chunks).toString();
} catch (err) {
this.logger.error(`error collecting response body chunk: ${err}`);
this.logger.verbose(err.stack);
}

return oldEnd.apply(res, args);
};
} catch (err) {
this.logger.error(`error setting response body to be collected: ${err}`);
this.logger.verbose(err.stack);
}

res.on('finish', () => {
const message = `${res.statusCode} ${res.statusMessage} | ${req.ip} | [${method}] ${url} - ${
Date.now() - requestStarted
Expand All @@ -30,6 +69,10 @@ export class HttpLoggerMiddleware implements NestMiddleware {
if (req.body) {
this.logger.debug(`request body: ${JSON.stringify(req.body)}`);
}

if (responseBody) {
this.logger.debug(`response body: ${responseBody}`);
}
});

res.on('close', () => {
Expand Down

0 comments on commit fcbee66

Please sign in to comment.