feat: 添加请求日志中间件以记录请求信息

Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
2026-04-24 22:41:18 +08:00
parent 81965595f0
commit aa53691dc7
2 changed files with 33 additions and 3 deletions
+26
View File
@@ -0,0 +1,26 @@
import { consola } from "consola";
/**
* 请求日志中间件:记录每次请求的 method、路径、状态码和耗时。
* 不记录请求体和响应体,避免密码、token 等敏感信息泄漏。
*/
export default defineEventHandler((event) => {
const start = Date.now();
const method = event.node.req.method ?? "UNKNOWN";
const path = getRequestURL(event).pathname;
// 响应发送完毕后记录结果
event.node.res.on("finish", () => {
const status = event.node.res.statusCode;
const elapsed = Date.now() - start;
const log = `[${method}] ${path}${status} (${elapsed}ms)`;
if (status >= 500) {
consola.error(log);
} else if (status >= 400) {
consola.warn(log);
} else {
consola.info(log);
}
});
});