AppLogger.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const fs = require('fs-extra');
  2. const Logger = require('./Logger');
  3. let instance = null;
  4. //singleton
  5. class AppLogger {
  6. constructor() {
  7. if (!instance) {
  8. this.inited = false;
  9. this.logFileName = '';
  10. this.errLogFileName = '';
  11. this.fatalLogFileName = '';
  12. instance = this;
  13. }
  14. return instance;
  15. }
  16. async init(config) {
  17. if (this.inited)
  18. throw new Error('already inited');
  19. let loggerParams = null;
  20. if (config.loggingEnabled) {
  21. await fs.ensureDir(config.logDir);
  22. this.logFileName = `${config.logDir}/${config.name}.log`;
  23. this.errLogFileName = `${config.logDir}/${config.name}.err.log`;
  24. this.fatalLogFileName = `${config.logDir}/${config.name}.fatal.log`;
  25. loggerParams = [
  26. {log: 'ConsoleLog'},
  27. {log: 'FileLog', fileName: this.logFileName},
  28. {log: 'FileLog', fileName: this.errLogFileName, exclude: [LM_OK, LM_INFO, LM_TOTAL]},
  29. {log: 'FileLog', fileName: this.fatalLogFileName, exclude: [LM_OK, LM_INFO, LM_WARN, LM_ERR, LM_TOTAL]},//LM_FATAL only
  30. ];
  31. }
  32. this._logger = new Logger(loggerParams);
  33. this.inited = true;
  34. return this.logger;
  35. }
  36. get logger() {
  37. if (!this.inited)
  38. throw new Error('not inited');
  39. return this._logger;
  40. }
  41. get log() {
  42. const l = this.logger;
  43. return l.log.bind(l);
  44. }
  45. }
  46. module.exports = AppLogger;