autosnippet
Version:
Extract code patterns into a knowledge base for AI coding assistants
25 lines (24 loc) • 1.2 kB
TypeScript
/**
* 请求日志中间件
* 使用 res.on('finish') 替代猴子补丁 res.send
*
* 精简策略:
* - GET 请求 + 2xx 状态码: 降为 debug(Dashboard 轮询高频噪音)
* - 非 GET / 非 2xx / 慢请求(>2s): 保留 info 级别
*
* ⚠️ 重要: 使用 req.originalUrl 而非 req.path。
* Express 4 子路由器 (app.use('/api/v1/x', router)) 会在执行
* handler 期间临时修改 req.url / req.path 为相对路径 (e.g. '/')。
* 当 res.on('finish') 同步触发时 req.url 尚未恢复,导致日志中
* 所有子路由请求都显示为 'GET / ...',SILENT_PATHS 匹配也失效。
* req.originalUrl 始终保持请求的原始 URL,不受路由挂载影响。
*/
import type { NextFunction, Request, Response } from 'express';
/** Minimal logger interface (compatible with winston.Logger) */
interface AppLogger {
info(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
debug(message: string, meta?: Record<string, unknown>): void;
}
export declare function requestLogger(logger: AppLogger): (req: Request, res: Response, next: NextFunction) => void;
export {};