Skip to content
Myr

index.ts

This file

Path

src/middleware/logger/index.ts

95 lines · 2.4 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–95why, one step back
1/**
2 * @module3 * Logger Middleware for Hono.4 */56import type { MiddlewareHandler } from '../../types'7import { getColorEnabledAsync } from '../../utils/color'89enum LogPrefix {10 Outgoing = '-->',11 Incoming = '<--',12 Error = 'xxx',13}1415const humanize = (times: string[]) => {16 const [delimiter, separator] = [',', '.']1718 const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + delimiter))1920 return orderTimes.join(separator)21}2223const time = (start: number) => {24 const delta = Date.now() - start25 return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])26}2728const colorStatus = async (status: number) => {29 const colorEnabled = await getColorEnabledAsync()30 if (colorEnabled) {31 switch ((status / 100) | 0) {32 case 5: // red = error33 return `\x1b[31m${status}\x1b[0m`34 case 4: // yellow = warning35 return `\x1b[33m${status}\x1b[0m`36 case 3: // cyan = redirect37 return `\x1b[36m${status}\x1b[0m`38 case 2: // green = success39 return `\x1b[32m${status}\x1b[0m`40 }41 }42 // Fallback to unsupported status code.43 // E.g.) Bun and Deno supports new Response with 101, but Node.js does not.44 // And those may evolve to accept more status.45 return `${status}`46}4748type PrintFunc = (str: string, ...rest: string[]) => void4950async function log(51 fn: PrintFunc,52 prefix: string,53 method: string,54 path: string,55 status: number = 0,56 elapsed?: string57) {58 const out =59 prefix === LogPrefix.Incoming60 ? `${prefix} ${method} ${path}`61 : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}`62 fn(out)63}6465/**66 * Logger Middleware for Hono.67 *68 * @see {@link https://hono.dev/docs/middleware/builtin/logger}69 *70 * @param {PrintFunc} [fn=console.log] - Optional function for customized logging behavior.71 * @returns {MiddlewareHandler} The middleware handler function.72 *73 * @example74 * ```ts75 * const app = new Hono()76 *77 * app.use(logger())78 * app.get('/', (c) => c.text('Hello Hono!'))79 * ```80 */81export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {82 return async function logger(c, next) {83 const { method, url } = c.req8485 const path = url.slice(url.indexOf('/', 8))8687 await log(fn, LogPrefix.Incoming, method, path)8889 const start = Date.now()9091 await next()9293 await log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start))94 }95}