1234567891011121314151617181920212223242526272829303132333435363738 |
- import { Context, Next } from 'koa';
- import { InterfaceLogger } from '@/plugins/logger';
- export default (logger: InterfaceLogger): (ctx: Context, next: Next) => Promise<void> => {
- const loggerMiddleware = async(ctx, next) => {
- const $log = logger(ctx);
- ctx.$log = $log;
- const a = Date.now();
- await next();
- const b = Date.now();
- if (ctx.response && ctx.status < 400) {
- const options: Record<string, string|number> = {
- time: b - a
- };
- if (ctx.request.body) {
- options.params = ctx.request.body;
- }
- $log.info('', options);
- }
- else {
- ctx.throw(ctx.status, ctx.response);
- }
- };
- return async(ctx: Context, next: Next) => {
- // 静态文件不处理
- const isApi = /^\/api/.test(ctx.url);
- if (!isApi) {
- await next();
- return;
- }
- return loggerMiddleware(ctx, next).catch(error => {
- const { status = 500 } = error;
- console.log(error);
- ctx.$log.error(error);
- ctx.status = status;
- });
- };
- };
|