auto_logger.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. /**
  3. * 自动记录日志
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/10/30
  7. * @version
  8. */
  9. const os = require('os');
  10. module.exports = options => {
  11. return function* autoLogger(next) {
  12. this.logId = this.app.uuid.v1();
  13. // 记录业务日志
  14. function getBussinessLogger(ctx) {
  15. if (ctx.url.match(/ledger/)) {
  16. return ctx.getLogger('ledger');
  17. } else if (ctx.url.match(/stage/)) {
  18. return ctx.getLogger('stage');
  19. }
  20. return ctx.getLogger('mixed');
  21. }
  22. if (this.url.indexOf('/public/') !== 0) {
  23. const bLogger = getBussinessLogger(this);
  24. if (this.session.sessionUser) {
  25. const logData = {
  26. method: this.method,
  27. user: this.session.sessionUser,
  28. project: this.session.sessionProject,
  29. data: this.request.body,
  30. };
  31. bLogger.info(JSON.stringify(logData));
  32. } else {
  33. const logData = {
  34. method: this.method,
  35. data: this.body,
  36. };
  37. bLogger.info(JSON.stringify(logData));
  38. }
  39. this.logInfo = { id: this.logId, time: new Date() };
  40. const cpus = os.cpus();
  41. this.logInfo.cpus = cpus.map(x => {
  42. return `${((1-x.times.idle/(x.times.idle+x.times.user+x.times.nice+x.times.sys+x.times.irq))*100).toFixed(2)}%`
  43. });
  44. yield this.service.globalLog.requestLog(this.request.body.data);
  45. }
  46. yield next;
  47. };
  48. };