u
This commit is contained in:
@@ -1,19 +1,54 @@
|
||||
import chalk from 'chalk';
|
||||
|
||||
export const loggerMiddleware = (req, res, next) => {
|
||||
const start = Date.now();
|
||||
res.on('finish', () => {
|
||||
const duration = Date.now() - start;
|
||||
const method = chalk.bold.blue(req.method.padEnd(7));
|
||||
const url = req.originalUrl;
|
||||
let status = res.statusCode;
|
||||
|
||||
if (status >= 500) status = chalk.red(status);
|
||||
else if (status >= 400) status = chalk.yellow(status);
|
||||
else if (status >= 300) status = chalk.cyan(status);
|
||||
else status = chalk.green(status);
|
||||
function safeJson(value) {
|
||||
try {
|
||||
return JSON.stringify(value, null, 2);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`${method} ${url} ${status} ${chalk.gray(`(${duration}ms)`)}`);
|
||||
});
|
||||
next();
|
||||
function captureResponseBody(res) {
|
||||
let body;
|
||||
const originalJson = res.json.bind(res);
|
||||
const originalSend = res.send.bind(res);
|
||||
|
||||
res.json = (payload) => {
|
||||
body = payload;
|
||||
return originalJson(payload);
|
||||
};
|
||||
|
||||
res.send = (payload) => {
|
||||
if (body === undefined) {
|
||||
body = payload;
|
||||
}
|
||||
return originalSend(payload);
|
||||
};
|
||||
|
||||
return () => body;
|
||||
}
|
||||
|
||||
export const loggerMiddleware = (req, res, next) => {
|
||||
const start = Date.now();
|
||||
const getBody = captureResponseBody(res);
|
||||
|
||||
res.on('finish', () => {
|
||||
const duration = Date.now() - start;
|
||||
const method = chalk.bold.blue(req.method.padEnd(7));
|
||||
const url = req.originalUrl;
|
||||
let status = res.statusCode;
|
||||
|
||||
if (status >= 500) status = chalk.red(status);
|
||||
else if (status >= 400) status = chalk.yellow(status);
|
||||
else if (status >= 300) status = chalk.cyan(status);
|
||||
else status = chalk.green(status);
|
||||
|
||||
console.log(`${method} ${url} ${status} ${chalk.gray(`(${duration}ms)`)}`);
|
||||
console.log(chalk.gray(' params:'), safeJson(req.params ?? {}));
|
||||
console.log(chalk.gray(' query:'), safeJson(req.query ?? {}));
|
||||
console.log(chalk.gray(' body:'), safeJson(req.body ?? {}));
|
||||
console.log(chalk.gray(' response:'), safeJson(getBody()));
|
||||
});
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user