import log4js from "logger"; const logger = log4js.getLogger("ERROR"); /** 路径/路由类「找不到」:只打控制台,不落盘(避免扫描、错 URL 等刷爆 running.log) */ function isPathNotFoundLikeError(error: unknown): boolean { if (!error || typeof error !== "object") return false; const e = error as NodeJS.ErrnoException & { statusCode?: number; statusMessage?: string }; const code = typeof e.code === "string" ? e.code : ""; if (code === "ENOENT" || code === "ENOTDIR") return true; if (e.statusCode !== 404) return false; const sm = (e.statusMessage ?? "").trim(); if (!sm) return true; if (/^not found$/i.test(sm)) return true; if (/page not found/i.test(sm)) return true; if (/^cannot (get|post|put|delete|patch|head)\b/i.test(sm)) return true; if (/no route found|cannot find.*route|static asset.*not found/i.test(sm)) return true; return false; } const processHandlersKey = "__personPanelErrorLoggerProcessHandlers"; function installProcessErrorLogging() { const g = globalThis as typeof globalThis & { [processHandlersKey]?: boolean }; if (g[processHandlersKey]) return; g[processHandlersKey] = true; process.on("unhandledRejection", (reason) => { if (reason instanceof Error) { logger.error("[unhandledRejection]", reason.message, reason.stack ?? ""); } else { logger.error("[unhandledRejection]", String(reason)); } }); process.on("uncaughtException", (err) => { logger.error("[uncaughtException]", err.message, err.stack ?? ""); }); } if (import.meta.dev) { console.log("plugin: 03.error-logger"); } export default defineNitroPlugin((nitroApp) => { installProcessErrorLogging(); nitroApp.hooks.hook("error", (error, context) => { const event = context.event; const tags = Array.isArray(context.tags) ? (context.tags as string[]).join(",") : ""; const prefix = [ event?.method ?? "", event?.path ?? "(no request)", tags ? `[${tags}]` : "", ] .filter(Boolean) .join(" "); if (isPathNotFoundLikeError(error)) { console.error(prefix || "(error)", "\n", error); return; } logger.error(prefix, "\n", error); }); });