123456789101112131415161718192021222324252627282930313233343536373839 |
- import { Context, Next } from 'koa';
- import { InterfaceLogger, commonInfo, output } from '@/plugins/logger';
- export default (logger: InterfaceLogger) => {
- 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 commonInfo: commonInfo = {
- ip: ctx.ip,
- time: b - a
- };
- if (ctx.request.body) {
- commonInfo.params = ctx.request.body;
- };
- $log.info(output(ctx, null, commonInfo))
- }
- 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 { body, status = 500, message } = error;
- const errorText = `res: ${JSON.stringify({ status, message, body })}`;
- ctx.$log.error(errorText);
- ctx.status = status
- });
- };
- };
|