Add logging
This commit is contained in:
parent
2a6153002c
commit
8814658142
11 changed files with 826 additions and 55 deletions
50
src/middleware/requestLoggerMiddleware.ts
Normal file
50
src/middleware/requestLoggerMiddleware.ts
Normal 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();
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue