refactor: the log middleware and its tests (#394)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor: the log middleware and its tests * fix: the time function in log middleware
authored by Miguel Oliveira · committed by GitHub · parent c63d7ed · Browse files · 2 files·+55 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+55 added−30 removed
- tests:+32 added−11 removed
- other:+23 added−19 removed
Provenance
- Commit
4e38e13- Tree
cdd9ce1- Author
Miguel Oliveira <88039515+migueloliveiraz@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
c63d7ed
2 files changed+55 added−30 removed
modified:src/middleware/logger/index.test.ts+32 added-11 removed
12345567789108910111212131314151617181920211516171822232425262728293031323334353616 unmodified lines535455565758596061626364656667688 unmodified linesimport { Hono } from '../../hono'import { logger } from '.'
describe('Logger by Middleware', () => { const app = new Hono() let app: Hono let log: string
let log = '' const logFn = (str: string) => { log = str } beforeEach(() => { function sleep (time: number) { return new Promise((resolve) => setTimeout(resolve, time)) }
const shortRandomString = 'hono' const longRandomString = 'hono'.repeat(1000) app = new Hono()
const logFn = (str: string) => { log = str } const shortRandomString = 'hono' const longRandomString = 'hono'.repeat(1000) app.use('*', logger(logFn)) app.get('/short', (c) => c.text(shortRandomString)) app.get('/long', (c) => c.text(longRandomString)) app.get('/empty', (c) => c.text('')) app.use('*', logger(logFn)) app.get('/short', (c) => c.text(shortRandomString)) app.get('/long', (c) => c.text(longRandomString)) app.get('/seconds', async (c) => { await sleep(1000)
return c.text(longRandomString) }) app.get('/empty', (c) => c.text('')) })
it('Log status 200 with empty body', async () => { const res = await app.request('http://localhost/empty') expect(res).not.toBeNull() expect(res.status).toBe(200)16 unmodified lines expect(log.startsWith(' --> GET /long \x1b[32m200\x1b[0m')).toBe(true) expect(log).toMatch(/m?s$/) })
it('Time in seconds', async () => { const res = await app.request('http://localhost/seconds') expect(res).not.toBeNull() expect(res.status).toBe(200) expect(log.startsWith(' --> GET /seconds \x1b[32m200\x1b[0m')).toBe(true) expect(log).toMatch(/1s/) })
it('Log status 404', async () => { const msg = 'Default 404 Not Found' app.all('*', (c) => { return c.text(msg, 404)8 unmodified linesmodified:src/middleware/logger/index.ts+23 added-19 removed
123456789101156789101112131415161718192016212223192021222324252625262728293031323334353536373839404142434445464744484950515253545556575458596061624 unmodified lines676869706771import type { Context } from '../../context'import type { Next } from '../../hono'import { getPathFromURL } from '../../utils/url'
const humanize = (n: string[], opts?: { delimiter?: string; separator?: string }) => { const options = opts || {} const d = options.delimiter || ',' const s = options.separator || '.' n = n.toString().split('.') n[0] = n[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + d) return n.join(s)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 < 10000 ? delta + 'ms' : Math.round(delta / 1000) + 's']) return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])}
const LogPrefix = { Outgoing: '-->', Incoming: '<--', Error: 'xxx',}
const colorStatus = (status: number = 0) => { const out: { [key: number]: string } = {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`, } return out[(status / 100) | 0]
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, 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 = console.log) => {export const logger = (fn: PrintFunc) => { return async (c: Context, next: Next) => { const { method } = c.req const path = getPathFromURL(c.req.url)
4 unmodified lines await next()
log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start)) }}}No newline at end of file