Skip to content

Commit

Permalink
chore: adding req & client IP & res bodies to the access log
Browse files Browse the repository at this point in the history
  • Loading branch information
artursudnik committed Oct 17, 2023
1 parent 14ea086 commit 069325b
Showing 1 changed file with 48 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,48 @@ export class AccessLog 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 delay = Date.now() - now;
const message = `${res.statusCode} | [${method}] ${url} - ${delay}ms`;
const message = `${res.statusCode} ${res.statusMessage} | ${req.ip} | [${method}] ${url} - ${delay}ms`;

finished = true;

Expand All @@ -42,6 +81,14 @@ export class AccessLog implements NestMiddleware {
} else {
this.logger.log(message);
}

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 069325b

Please sign in to comment.