logs.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { Context, Next } from 'koa';
  2. import { InterfaceLogger } from '@/plugins/logger';
  3. export default (logger: InterfaceLogger): (ctx: Context, next: Next) => Promise<void> => {
  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 options: Record<string, string|number> = {
  12. time: b - a
  13. };
  14. if (ctx.request.body) {
  15. options.params = ctx.request.body;
  16. }
  17. $log.info('', options);
  18. }
  19. else {
  20. ctx.throw(ctx.status, ctx.response);
  21. }
  22. };
  23. return async(ctx: Context, next: Next) => {
  24. // 静态文件不处理
  25. const isApi = /^\/api/.test(ctx.url);
  26. if (!isApi) {
  27. await next();
  28. return;
  29. }
  30. return loggerMiddleware(ctx, next).catch(error => {
  31. const { status = 500 } = error;
  32. console.log(error);
  33. ctx.$log.error(error);
  34. ctx.status = status;
  35. });
  36. };
  37. };