Add compact colored prettyJson helper for request logs.

This commit is contained in:
seb
2026-08-01 04:40:32 +02:00
parent 71c8507805
commit bdcd745c4d
2 changed files with 215 additions and 32 deletions

View File

@@ -1,33 +1,16 @@
import chalk from 'chalk';
import { isEmpty, prettyJson } from '../../util/prettyJson.js';
const BINARY_PREVIEW_BYTES = 16;
function summarizeBuffer(buf) {
const head = buf.subarray(0, BINARY_PREVIEW_BYTES);
const hex = [...head].map((b) => b.toString(16).padStart(2, '0')).join(' ');
return {
type: 'Buffer',
length: buf.length,
headHex: hex,
};
}
function safeJson(value) {
try {
if (Buffer.isBuffer(value)) {
return JSON.stringify(summarizeBuffer(value), null, 2);
}
if (
Array.isArray(value) &&
value.length > 64 &&
value.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)
) {
return JSON.stringify(summarizeBuffer(Buffer.from(value)), null, 2);
}
return JSON.stringify(value, null, 2);
} catch {
return String(value);
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);
return;
}
console.log(prefix);
console.log(rendered.replace(/^/gm, ' '));
}
function captureResponseBody(res) {
@@ -66,11 +49,13 @@ export const loggerMiddleware = (req, res, next) => {
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(' content-type:'), req.headers['content-type'] ?? '(none)');
console.log(chalk.gray(' body:'), safeJson(req.body ?? {}));
console.log(chalk.gray(' response:'), safeJson(getBody()));
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']));
}
logField('body', req.body ?? {}, { skipEmpty: true });
logField('response', getBody());
});
next();