32 lines
1 KiB
TypeScript
32 lines
1 KiB
TypeScript
/**
|
|
* Lightweight HTTP request logger that records method, url, status and duration
|
|
* for every incoming request. Skips noisy probe endpoints to keep logs clean.
|
|
*/
|
|
import type { Request, Response, NextFunction } from "express";
|
|
import { childLogger } from "./logger.js";
|
|
|
|
const httpLog = childLogger("http");
|
|
|
|
const SKIP_PATHS = new Set(["/api/live", "/api/ready", "/api/health"]);
|
|
|
|
export function requestLogger(req: Request, res: Response, next: NextFunction): void {
|
|
if (SKIP_PATHS.has(req.path)) return next();
|
|
|
|
const startNs = process.hrtime.bigint();
|
|
|
|
res.on("finish", () => {
|
|
const durationMs = Number((process.hrtime.bigint() - startNs) / 1_000_000n);
|
|
const status = res.statusCode;
|
|
const payload = {
|
|
method: req.method,
|
|
url: req.originalUrl ?? req.url,
|
|
status,
|
|
durationMs,
|
|
};
|
|
if (status >= 500) httpLog.error(payload, "request failed");
|
|
else if (status >= 400) httpLog.warn(payload, "request error");
|
|
else httpLog.info(payload, "request ok");
|
|
});
|
|
|
|
next();
|
|
}
|