Add logging

This commit is contained in:
araemer 2025-11-20 19:58:14 +01:00
parent 2a6153002c
commit 8814658142
11 changed files with 826 additions and 55 deletions

View file

@ -0,0 +1,50 @@
import { Request, Response, NextFunction } from "express";
import { logger, logRequest } from "../utils/logger.js";
/**
* Middleware to log all incoming requests and their responses
* Logs: method, path, status code, response time, and user info
*/
export const requestLoggerMiddleware = (
req: Request,
res: Response,
next: NextFunction
) => {
const startTime = Date.now();
// Get the full URL path (baseUrl + path)
const fullPath = req.baseUrl + req.path;
// Log incoming request
const userId = req.currentUser?.id || "anonymous";
logger.info(`${req.method} ${fullPath} (User: ${userId})`);
// Capture the original res.json and res.send to log response
const originalJson = res.json.bind(res);
const originalSend = res.send.bind(res);
// Override res.json
res.json = function (body: any) {
const duration = Date.now() - startTime;
logRequest(req.method, fullPath, res.statusCode, duration);
return originalJson(body);
};
// Override res.send
res.send = function (body: any) {
const duration = Date.now() - startTime;
logRequest(req.method, fullPath, res.statusCode, duration);
return originalSend(body);
};
// Handle responses that end without json/send
res.on("finish", () => {
// Only log if we haven't already logged (json/send weren't called)
if (!res.headersSent) {
const duration = Date.now() - startTime;
logRequest(req.method, fullPath, res.statusCode, duration);
}
});
next();
};