0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 10:51:01 +00:00
hono/deno_dist/middleware/logger/index.ts

71 lines
1.7 KiB
TypeScript
Raw Normal View History

import type { MiddlewareHandler } from '../../types.ts'
2022-07-02 06:09:45 +00:00
import { getPathFromURL } from '../../utils/url.ts'
2022-07-17 09:11:09 +00:00
enum LogPrefix {
Outgoing = '-->',
Incoming = '<--',
Error = 'xxx',
2022-07-02 06:09:45 +00:00
}
2022-07-17 09:11:09 +00:00
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)
2022-07-02 06:09:45 +00:00
}
2022-07-17 09:11:09 +00:00
const time = (start: number) => {
const delta = Date.now() - start
return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])
2022-07-02 06:09:45 +00:00
}
2022-07-17 09:11:09 +00:00
const colorStatus = (status: number) => {
const out: { [key: string]: string } = {
2022-07-02 06:09:45 +00:00
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`,
}
2022-07-17 09:11:09 +00:00
const calculateStatus = (status / 100) | 0
return out[calculateStatus]
2022-07-02 06:09:45 +00:00
}
2022-07-17 09:11:09 +00:00
2022-07-02 06:09:45 +00:00
type PrintFunc = (str: string, ...rest: string[]) => void
function log(
fn: PrintFunc,
prefix: string,
method: string,
path: string,
2022-07-17 09:11:09 +00:00
status: number = 0,
2022-07-02 06:09:45 +00:00
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) => {
2022-07-02 06:09:45 +00:00
const { method } = c.req
2023-01-10 12:24:21 +00:00
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [path, _] = getPathFromURL(c.req.url)
2022-07-02 06:09:45 +00:00
log(fn, LogPrefix.Incoming, method, path)
const start = Date.now()
await next()
log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start))
}
}