Files
SnowLuma/.pnpm-store/v11/files/90/cc64f4315112665f2ed8319f56bd5979fd81314d1379e645e27483f45632dcd175156f4ae44ba86df44969c19a380dffdb07b04f38238856d856cff602daac
TanTan 2a69b23b47
Dev Build / cleanup (push) Canceled after 0s
Dev Build / typecheck (push) Canceled after 0s
Dev Build / build (linux-arm64, ubuntu-24.04-arm, linux-arm64) (push) Canceled after 0s
Dev Build / build (linux-x64, ubuntu-latest, linux-x64) (push) Canceled after 0s
Dev Build / build (win-x64, windows-latest, win32-x64) (push) Canceled after 0s
Dev Build / dispatch-dev-docker (push) Canceled after 0s
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

51 lines
1.6 KiB
Plaintext

import { getColorEnabledAsync } from "../../utils/color.js";
//#region src/middleware/logger/index.ts
const humanize = (times) => {
const [delimiter, separator] = [",", "."];
return times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter)).join(separator);
};
const time = (start) => {
const delta = Date.now() - start;
return humanize([delta < 1e3 ? delta + "ms" : Math.round(delta / 1e3) + "s"]);
};
const colorStatus = async (status) => {
if (await getColorEnabledAsync()) switch (status / 100 | 0) {
case 5: return `\x1b[31m${status}\x1b[0m`;
case 4: return `\x1b[33m${status}\x1b[0m`;
case 3: return `\x1b[36m${status}\x1b[0m`;
case 2: return `\x1b[32m${status}\x1b[0m`;
}
return `${status}`;
};
async function log(fn, prefix, method, path, status = 0, elapsed) {
fn(prefix === "<--" ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`);
}
/**
* Logger Middleware for Hono.
*
* @see {@link https://hono.dev/docs/middleware/builtin/logger}
*
* @param {PrintFunc} [fn=console.log] - Optional function for customized logging behavior.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(logger())
* app.get('/', (c) => c.text('Hello Hono!'))
* ```
*/
const logger = (fn = console.log) => {
return async function logger(c, next) {
const { method, url } = c.req;
const path = url.slice(url.indexOf("/", 8));
await log(fn, "<--", method, path);
const start = Date.now();
await next();
await log(fn, "-->", method, path, c.res.status, time(start));
};
};
//#endregion
export { logger };