auto_logger.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. // 记录业务日志
  13. function getBussinessLogger(ctx) {
  14. if (ctx.url.match(/ledger/)) {
  15. return ctx.getLogger('ledger');
  16. } else if (ctx.url.match(/stage/)) {
  17. return ctx.getLogger('stage');
  18. }
  19. return ctx.getLogger('mixed');
  20. }
  21. const bLogger = getBussinessLogger(this);
  22. if (this.session.sessionUser) {
  23. const logData = {
  24. method: this.method,
  25. user: this.session.sessionUser,
  26. project: this.session.sessionProject,
  27. data: this.request.body,
  28. };
  29. bLogger.info(JSON.stringify(logData));
  30. } else {
  31. const logData = {
  32. method: this.method,
  33. data: this.body,
  34. };
  35. bLogger.info(JSON.stringify(logData));
  36. }
  37. this.logInfo = { time: new Date() };
  38. const cpus = os.cpus();
  39. this.logInfo.cpus = cpus.map(x => {
  40. return `${((1-x.times.idle/(x.times.idle+x.times.user+x.times.nice+x.times.sys+x.times.irq))*100).toFixed(2)}%`
  41. });
  42. // 自动记录log的action
  43. // const autoLogAction = ['save', 'delete'];
  44. // if (this.actionName !== undefined && autoLogAction.indexOf(this.actionName) >= 0) {
  45. // // 操作数据的id
  46. // const idReg = /\/(\d+)/;
  47. // const paramInfo = this.request.originalUrl.match(idReg);
  48. // let targetId = paramInfo[1] !== undefined ? paramInfo[1] : -1;
  49. // targetId = parseInt(targetId);
  50. //
  51. // const logData = {
  52. // controller: this.controllerName,
  53. // action: this.actionName,
  54. // operation: this.currentName === undefined ? '保存数据' : this.currentName,
  55. // target_id: targetId,
  56. // };
  57. // yield this.service.log.addLog(logData);
  58. // }
  59. yield next;
  60. };
  61. };