logs.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { Context, Next } from 'koa';
  2. import { InterfaceLogger, commonInfo, output } from '@/plugins/logger';
  3. export default (logger: InterfaceLogger) => {
  4. const loggerMiddleware = async(ctx, next) => {
  5. const $log = logger(ctx)
  6. ctx.$log = $log;
  7. const a = Date.now()
  8. await next();
  9. const b = Date.now()
  10. if (ctx.response && ctx.status < 400) {
  11. const commonInfo: commonInfo = {
  12. ip: ctx.ip,
  13. time: b - a
  14. };
  15. if (ctx.request.body) {
  16. commonInfo.params = ctx.request.body;
  17. };
  18. $log.info(output(ctx, null, commonInfo))
  19. }
  20. else {
  21. ctx.throw(ctx.status, ctx.response);
  22. }
  23. }
  24. return async(ctx: Context, next: Next) => {
  25. // 静态文件不处理
  26. const isApi = /^\/api/.test(ctx.url);
  27. if (!isApi) {
  28. await next();
  29. return;
  30. };
  31. return loggerMiddleware(ctx, next).catch(error => {
  32. const { body, status = 500, message } = error;
  33. const errorText = `res: ${JSON.stringify({ status, message, body })}`;
  34. ctx.$log.error(errorText);
  35. ctx.status = status
  36. });
  37. };
  38. };