|
| 1 | +import type { Request, Response, NextFunction } from 'express' |
| 2 | + |
| 3 | +/** |
| 4 | + * Request logging middleware with timestamp, colored status codes, and MCP method info |
| 5 | + * |
| 6 | + * Logs all HTTP requests with: |
| 7 | + * - Timestamp in HH:MM:SS.mmm format |
| 8 | + * - HTTP method and endpoint in bold |
| 9 | + * - MCP method name in brackets for POST requests to /mcp |
| 10 | + * - Color-coded status codes (green 2xx, yellow 3xx, red 4xx, magenta 5xx) |
| 11 | + * |
| 12 | + * @param req - Express request object |
| 13 | + * @param res - Express response object |
| 14 | + * @param next - Express next function |
| 15 | + */ |
| 16 | +export function requestLogger(req: Request, res: Response, next: NextFunction): void { |
| 17 | + const timestamp = new Date().toISOString().substring(11, 23) |
| 18 | + const method = req.method |
| 19 | + const url = req.url |
| 20 | + |
| 21 | + // Override res.end to capture status code |
| 22 | + const originalEnd = res.end.bind(res) |
| 23 | + res.end = function(chunk?: any, encoding?: any, cb?: any) { |
| 24 | + const statusCode = res.statusCode |
| 25 | + let statusColor = '' |
| 26 | + |
| 27 | + if (statusCode >= 200 && statusCode < 300) { |
| 28 | + statusColor = '\x1b[32m' // Green for 2xx |
| 29 | + } else if (statusCode >= 300 && statusCode < 400) { |
| 30 | + statusColor = '\x1b[33m' // Yellow for 3xx |
| 31 | + } else if (statusCode >= 400 && statusCode < 500) { |
| 32 | + statusColor = '\x1b[31m' // Red for 4xx |
| 33 | + } else if (statusCode >= 500) { |
| 34 | + statusColor = '\x1b[35m' // Magenta for 5xx |
| 35 | + } |
| 36 | + |
| 37 | + // Add MCP method info for POST requests to /mcp |
| 38 | + let logMessage = `[${timestamp}] ${method} \x1b[1m${url}\x1b[0m` |
| 39 | + if (method === 'POST' && url === '/mcp' && req.body?.method) { |
| 40 | + logMessage += ` \x1b[1m[${req.body.method}]\x1b[0m` |
| 41 | + } |
| 42 | + logMessage += ` ${statusColor}${statusCode}\x1b[0m` |
| 43 | + |
| 44 | + console.log(logMessage) |
| 45 | + |
| 46 | + return originalEnd(chunk, encoding, cb) |
| 47 | + } |
| 48 | + |
| 49 | + next() |
| 50 | +} |
0 commit comments