import Koa from 'koa' import { IMiddleware } from 'koa-router' import { err, log } from '../logger' export default function logMiddle (): IMiddleware { return async (ctx, next: () => Promise) => { const start = Date.now() try { await next() const ms = Date.now() - start ctx.set('x-response-time', `${ms}ms`) log( 'Router Request', '\n' + [ `[path]: ${ctx.path}`, `[method]: ${ctx.method}`, `[elapsedtime]: ${ms}ms`, `[ip]: ${ctx.ip}`, `[ips]: ${ctx.ips}`, `[originalUrl]: ${ctx.originalUrl}`, `[headers]: ${JSON.stringify(ctx.headers)}`, `[params]: ${JSON.stringify(ctx.params)}`, `[query]: ${ctx.querystring}`, `[payload]: ${JSON.stringify(ctx.request.body)}`, `[return]: ${JSON.stringify(ctx.body)}` ].join(';\n') ) } catch (error) { const ms = Date.now() - start err( 'Router Error', error, '\n' + [ `[path]: ${ctx.path}`, `[method]: ${ctx.method}`, `[elapsedtime]: ${ms}ms`, `[ip]: ${ctx.ip}`, `[ips]: ${ctx.ips}`, `[originalUrl]: ${ctx.originalUrl}`, `[headers]: ${JSON.stringify(ctx.headers)}`, `[params]: ${JSON.stringify(ctx.params)}`, `[query]: ${ctx.querystring}`, `[payload]: ${JSON.stringify(ctx.request.body)}`, `[return]: ${JSON.stringify(ctx.body)}` ].join(';\n') ) throw error } } }