You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

56 lines
1.9 KiB

import log4js from "logger";
import { randomUUID } from "crypto";
import { STATIC_PUBLIC_PREFIX } from "../constants/upload";
const logger = log4js.getLogger("APP")
/** 静态文件慢请求阈值(ms),超过此值才在 dev 下打印日志 */
const STATIC_SLOW_THRESHOLD = 500
if (import.meta.dev) {
console.log("plugin: 00.req-time");
}
declare module "http" {
interface IncomingMessage {
$beginTime: number;
$requestId: string;
}
}
function isStaticGet(event: any): boolean {
if (!event.path.startsWith(STATIC_PUBLIC_PREFIX)) return false;
const method = event.node.req.method;
return method ? new Set(["HEAD", "GET"]).has(method) : false;
}
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('request', async (event) => {
const incoming = event.node.req.headers["x-request-id"];
const requestId =
typeof incoming === "string" && incoming.trim().length > 0
? incoming.trim()
: randomUUID();
event.node.req.$requestId = requestId;
event.node.req.$beginTime = new Date().getTime();
event.node.res.setHeader("X-Request-Id", requestId);
if (isStaticGet(event)) return;
logger.info(`[${requestId}]`, `[${event.method}-${event.path}]`, "开始请求");
})
nitroApp.hooks.hook('afterResponse', async (event) => {
const requestId = event.node.req.$requestId ?? "(no-request-id)";
const offsetTime = new Date().getTime() - (event.node.req.$beginTime ?? 0);
if (isStaticGet(event)) {
if (import.meta.dev && offsetTime > STATIC_SLOW_THRESHOLD) {
logger.info(`[${requestId}]`, `[STATIC]`, offsetTime, "ms");
}
return;
}
logger.info(`[${requestId}]`, `[${event.method}-${event.path}]`, "请求结束,花费了", offsetTime, "ms");
})
})