0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 11:51:01 +01:00
hono/deno_dist/middleware/logger/index.ts
Taku Amano b253a8735b
feat: Allow getPath to be replaced. (#1064)
* feat: Allow getPath to be replaced.

* chore: denoify
2023-05-03 22:13:23 +09:00

71 lines
1.7 KiB
TypeScript

import type { MiddlewareHandler } from '../../types.ts'
import { getPath } from '../../utils/url.ts'
enum LogPrefix {
Outgoing = '-->',
Incoming = '<--',
Error = 'xxx',
}
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'])
}
const colorStatus = (status: number) => {
const out: { [key: string]: string } = {
7: `\x1b[35m${status}\x1b[0m`,
5: `\x1b[31m${status}\x1b[0m`,
4: `\x1b[33m${status}\x1b[0m`,
3: `\x1b[36m${status}\x1b[0m`,
2: `\x1b[32m${status}\x1b[0m`,
1: `\x1b[32m${status}\x1b[0m`,
0: `\x1b[33m${status}\x1b[0m`,
}
const calculateStatus = (status / 100) | 0
return out[calculateStatus]
}
type PrintFunc = (str: string, ...rest: string[]) => void
function log(
fn: PrintFunc,
prefix: string,
method: string,
path: string,
status: number = 0,
elapsed?: string
) {
const out =
prefix === LogPrefix.Incoming
? ` ${prefix} ${method} ${path}`
: ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`
fn(out)
}
export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {
return async (c, next) => {
const { method } = c.req
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const path = getPath(c.req.raw)
log(fn, LogPrefix.Incoming, method, path)
const start = Date.now()
await next()
log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start))
}
}