This commit is contained in:
seb
2026-10-08 03:43:28 +02:00
parent c543c76a21
commit 717f4754d4
9 changed files with 787 additions and 24 deletions

View File

@@ -1,17 +1,18 @@
import chalk from 'chalk';
import { isEmpty, prettyJson } from '../../util/prettyJson.js';
import { writeErrorLog } from '../../util/errorLog.js';
import { createLogger, chalk } from '../../util/logger.js';
const httpLog = createLogger('http');
function logField(label, value, { skipEmpty = false } = {}) {
if (skipEmpty && isEmpty(value)) return;
const rendered = prettyJson(value);
const prefix = chalk.gray(` ${label}: `);
if (!rendered.includes('\n')) {
console.log(prefix + rendered);
httpLog.debug(prefix + rendered);
return;
}
console.log(prefix);
console.log(rendered.replace(/^/gm, ' '));
httpLog.debug(prefix + '\n' + rendered.replace(/^/gm, ' '));
}
function captureResponseBody(res) {
@@ -53,14 +54,22 @@ export const loggerMiddleware = (req, res, next) => {
else if (status >= 300) status = chalk.cyan(status);
else status = chalk.green(status);
console.log(`${method} ${url} ${status} ${chalk.gray(`(${duration}ms)`)}`);
const summary = `${method} ${url} ${status} ${chalk.gray(`(${duration}ms)`)}`;
if (res.statusCode >= 500) {
httpLog.error(summary);
} else if (res.statusCode >= 400) {
httpLog.warn(summary);
} else {
httpLog.info(summary);
}
logField('params', req.params ?? {}, { skipEmpty: true });
logField('query', req.query ?? {}, { skipEmpty: true });
if (req.headers['content-type']) {
console.log(chalk.gray(' content-type:'), chalk.cyan(req.headers['content-type']));
httpLog.debug(chalk.gray(' content-type: ') + chalk.cyan(req.headers['content-type']));
}
if (req.headers.authorization) {
console.log(chalk.gray(' authorization:'), chalk.cyan(req.headers.authorization));
httpLog.debug(chalk.gray(' authorization: ') + chalk.cyan(req.headers.authorization));
}
logField('body', req.body ?? {}, { skipEmpty: true });
logField('response', getBody());