hour_rotator.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const moment = require('moment');
  3. const fs = require('mz/fs');
  4. const path = require('path');
  5. const debug = require('debug')('egg-logrotator:hour_rotator');
  6. const Rotator = require('./rotator');
  7. // rotate log by hour
  8. // rename from foo.log to foo.log.YYYY-MM-DD-HH
  9. class DayRotator extends Rotator {
  10. async getRotateFiles() {
  11. const files = new Map();
  12. const logDir = this.app.config.logger.dir;
  13. const filesRotateByHour = this.app.config.logrotator.filesRotateByHour || [];
  14. for (let logPath of filesRotateByHour) {
  15. // support relative path
  16. if (!path.isAbsolute(logPath)) logPath = path.join(logDir, logPath);
  17. const exists = await fs.exists(logPath);
  18. if (!exists) {
  19. continue;
  20. }
  21. this._setFile(logPath, files);
  22. }
  23. return files;
  24. }
  25. get hourDelimiter() {
  26. return this.app.config.logrotator.hourDelimiter;
  27. }
  28. _setFile(srcPath, files) {
  29. if (!files.has(srcPath)) {
  30. const targetPath = srcPath + moment().subtract(1, 'hours').format(`.YYYY-MM-DD${this.hourDelimiter}HH`);
  31. debug('set file %s => %s', srcPath, targetPath);
  32. files.set(srcPath, { srcPath, targetPath });
  33. }
  34. }
  35. }
  36. module.exports = DayRotator;