Skip to main content
Home

latest
It is unknown whether this package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
It is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Node.js
It is unknown whether this package works with Deno
It is unknown whether this package works with Bun
It is unknown whether this package works with Browsers
JSR Score
35%
Published
2 months ago (0.1.12)
import type { Route } from "../mod.ts"; type PrintFunc = (str: string, ...rest: string[]) => void; const colorStatus = (status: number) => { const colorEnabled = true; if (colorEnabled) { switch ((status / 100) | 0) { case 5: // red = error return `\x1b[31m${status}\x1b[0m`; case 4: // yellow = warning return `\x1b[33m${status}\x1b[0m`; case 3: // cyan = redirect return `\x1b[36m${status}\x1b[0m`; case 2: // green = success return `\x1b[32m${status}\x1b[0m`; } } // Fallback to unsupported status code. // E.g.) Bun and Deno supports new Response with 101, but Node.js does not. // And those may evolve to accept more status. return `${status}`; }; const log = ( fn: PrintFunc, prefix: string, method: string, path: string, status = 0, elapsed?: string, ) => { const out = prefix === "<--" ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`; fn(out); }; const humanize = (times: string[]) => { const [delimiter, separator] = [",", "."]; const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, `$1${delimiter}`) ); return orderTimes.join(separator); }; const time = (start: number) => { const delta = Date.now() - start; return humanize([ delta < 1000 ? `${delta}ms` : `${Math.round(delta / 1000)}s`, ]); }; export const logger: <T>(options?: { log?: PrintFunc }) => Route<T>[] = ( options, ) => [{ method: [ "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "TRACE", "CONNECT", ], pattern: new URLPattern({ pathname: "*" }), handler: async ({ next, request }) => { const fn = options?.log ?? console.log; const { method, url } = request; const path = url.slice(url.indexOf("/", 8)); log(fn, "<--", method, path); const start = Date.now(); const res = await next(); log(fn, "-->", method, path, res.status, time(start)); return res; }, }];