Spaces:
Running
Running
File size: 1,521 Bytes
3d97d52 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
/**
* AI-generated file using Cursor + Claude 4
*
* Middleware to log all HTTP requests with duration, status code, method, and route
*/
import { type Request, type Response, type NextFunction } from "express";
interface LogContext {
timestamp: string;
method: string;
url: string;
statusCode?: number;
duration?: number;
}
function formatLogMessage(context: LogContext): string {
const { timestamp, method, url, statusCode, duration } = context;
if (statusCode === undefined) {
return `[${timestamp}] 📥 ${method} ${url}`;
}
const statusEmoji =
statusCode >= 200 && statusCode < 300
? "✅"
: statusCode >= 400 && statusCode < 500
? "⚠️"
: statusCode >= 500
? "❌"
: "ℹ️";
return `[${timestamp}] ${statusEmoji} ${statusCode} ${method} ${url} (${duration}ms)`;
}
/**
* Middleware to log all HTTP requests with duration, status code, method, and route
*/
export function requestLogger() {
return (req: Request, res: Response, next: NextFunction): void => {
const startTime = Date.now();
const { method, url } = req;
// Log incoming request
console.log(
formatLogMessage({
timestamp: new Date().toISOString(),
method,
url,
})
);
// Listen for when the response finishes
res.on("finish", () => {
const duration = Date.now() - startTime;
console.log(
formatLogMessage({
timestamp: new Date().toISOString(),
method,
url,
statusCode: res.statusCode,
duration,
})
);
});
next();
};
}
|