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
51 lines
1.6 KiB
Plaintext
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 };
|