rotator.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const assert = require('assert');
  3. const fs = require('mz/fs');
  4. const debug = require('debug')('egg-logrotator:rotator');
  5. class Rotator {
  6. constructor(options) {
  7. this.options = options || {};
  8. assert(this.options.app, 'options.app is required');
  9. this.app = this.options.app;
  10. this.logger = this.app.coreLogger;
  11. }
  12. getRotateFiles() {
  13. throw new Error('not implement');
  14. }
  15. async rotate() {
  16. const files = await this.getRotateFiles();
  17. assert(files instanceof Map, 'getRotateFiles should return a Map');
  18. const rotatedFile = [];
  19. for (const file of files.values()) {
  20. try {
  21. debug('rename from %s to %s', file.srcPath, file.targetPath);
  22. await renameOrDelete(file.srcPath, file.targetPath);
  23. rotatedFile.push(`${file.srcPath} -> ${file.targetPath}`);
  24. } catch (err) {
  25. err.message = `[egg-logrotator] rename ${file.srcPath}, found exception: ` + err.message;
  26. this.logger.error(err);
  27. }
  28. }
  29. if (rotatedFile.length) {
  30. // tell every one to reload logger
  31. this.logger.info('[egg-logrotator] broadcast log-reload');
  32. this.app.messenger.sendToApp('log-reload');
  33. this.app.messenger.sendToAgent('log-reload');
  34. }
  35. this.logger.info('[egg-logrotator] rotate files success by %s, files %j',
  36. this.constructor.name, rotatedFile);
  37. }
  38. }
  39. module.exports = Rotator;
  40. // rename from srcPath to targetPath, for example foo.log.1 > foo.log.2
  41. async function renameOrDelete(srcPath, targetPath) {
  42. if (srcPath === targetPath) {
  43. return;
  44. }
  45. const srcExists = await fs.exists(srcPath);
  46. if (!srcExists) {
  47. return;
  48. }
  49. const targetExists = await fs.exists(targetPath);
  50. // if target file exists, then throw
  51. // because the target file always be renamed first.
  52. if (targetExists) {
  53. const err = new Error(`targetFile ${targetPath} exists!!!`);
  54. throw err;
  55. }
  56. await fs.rename(srcPath, targetPath);
  57. }