@eggjs/logrotator 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -0
  3. package/README.zh-CN.md +115 -0
  4. package/dist/commonjs/agent.d.ts +2 -0
  5. package/dist/commonjs/agent.js +5 -0
  6. package/dist/commonjs/app/extend/agent.d.ts +5 -0
  7. package/dist/commonjs/app/extend/agent.js +8 -0
  8. package/dist/commonjs/app/extend/application.d.ts +5 -0
  9. package/dist/commonjs/app/extend/application.js +7 -0
  10. package/dist/commonjs/app/schedule/clean_log.d.ts +9 -0
  11. package/dist/commonjs/app/schedule/clean_log.js +74 -0
  12. package/dist/commonjs/app/schedule/rotate_by_file.d.ts +10 -0
  13. package/dist/commonjs/app/schedule/rotate_by_file.js +17 -0
  14. package/dist/commonjs/app/schedule/rotate_by_hour.d.ts +10 -0
  15. package/dist/commonjs/app/schedule/rotate_by_hour.js +17 -0
  16. package/dist/commonjs/app/schedule/rotate_by_size.d.ts +10 -0
  17. package/dist/commonjs/app/schedule/rotate_by_size.js +17 -0
  18. package/dist/commonjs/app.d.ts +2 -0
  19. package/dist/commonjs/app.js +5 -0
  20. package/dist/commonjs/boot.d.ts +6 -0
  21. package/dist/commonjs/boot.js +18 -0
  22. package/dist/commonjs/config/config.default.d.ts +64 -0
  23. package/dist/commonjs/config/config.default.js +16 -0
  24. package/dist/commonjs/index.d.ts +2 -0
  25. package/dist/commonjs/index.js +19 -0
  26. package/dist/commonjs/lib/day_rotator.d.ts +8 -0
  27. package/dist/commonjs/lib/day_rotator.js +89 -0
  28. package/dist/commonjs/lib/hour_rotator.d.ts +6 -0
  29. package/dist/commonjs/lib/hour_rotator.js +46 -0
  30. package/dist/commonjs/lib/rotator.d.ts +16 -0
  31. package/dist/commonjs/lib/rotator.js +78 -0
  32. package/dist/commonjs/lib/size_rotator.d.ts +5 -0
  33. package/dist/commonjs/lib/size_rotator.js +73 -0
  34. package/dist/commonjs/lib/utils.d.ts +11 -0
  35. package/dist/commonjs/lib/utils.js +24 -0
  36. package/dist/commonjs/package.json +3 -0
  37. package/dist/commonjs/types.d.ts +11 -0
  38. package/dist/commonjs/types.js +3 -0
  39. package/dist/esm/agent.d.ts +2 -0
  40. package/dist/esm/agent.js +3 -0
  41. package/dist/esm/app/extend/agent.d.ts +5 -0
  42. package/dist/esm/app/extend/agent.js +6 -0
  43. package/dist/esm/app/extend/application.d.ts +5 -0
  44. package/dist/esm/app/extend/application.js +5 -0
  45. package/dist/esm/app/schedule/clean_log.d.ts +9 -0
  46. package/dist/esm/app/schedule/clean_log.js +69 -0
  47. package/dist/esm/app/schedule/rotate_by_file.d.ts +10 -0
  48. package/dist/esm/app/schedule/rotate_by_file.js +15 -0
  49. package/dist/esm/app/schedule/rotate_by_hour.d.ts +10 -0
  50. package/dist/esm/app/schedule/rotate_by_hour.js +15 -0
  51. package/dist/esm/app/schedule/rotate_by_size.d.ts +10 -0
  52. package/dist/esm/app/schedule/rotate_by_size.js +15 -0
  53. package/dist/esm/app.d.ts +2 -0
  54. package/dist/esm/app.js +3 -0
  55. package/dist/esm/boot.d.ts +6 -0
  56. package/dist/esm/boot.js +14 -0
  57. package/dist/esm/config/config.default.d.ts +64 -0
  58. package/dist/esm/config/config.default.js +14 -0
  59. package/dist/esm/index.d.ts +2 -0
  60. package/dist/esm/index.js +3 -0
  61. package/dist/esm/lib/day_rotator.d.ts +8 -0
  62. package/dist/esm/lib/day_rotator.js +82 -0
  63. package/dist/esm/lib/hour_rotator.d.ts +6 -0
  64. package/dist/esm/lib/hour_rotator.js +39 -0
  65. package/dist/esm/lib/rotator.d.ts +16 -0
  66. package/dist/esm/lib/rotator.js +71 -0
  67. package/dist/esm/lib/size_rotator.d.ts +5 -0
  68. package/dist/esm/lib/size_rotator.js +66 -0
  69. package/dist/esm/lib/utils.d.ts +11 -0
  70. package/dist/esm/lib/utils.js +21 -0
  71. package/dist/esm/package.json +3 -0
  72. package/dist/esm/types.d.ts +11 -0
  73. package/dist/esm/types.js +2 -0
  74. package/dist/package.json +4 -0
  75. package/package.json +101 -0
  76. package/src/agent.ts +3 -0
  77. package/src/app/extend/agent.ts +6 -0
  78. package/src/app/extend/application.ts +5 -0
  79. package/src/app/schedule/clean_log.ts +74 -0
  80. package/src/app/schedule/rotate_by_file.ts +18 -0
  81. package/src/app/schedule/rotate_by_hour.ts +19 -0
  82. package/src/app/schedule/rotate_by_size.ts +18 -0
  83. package/src/app.ts +3 -0
  84. package/src/boot.ts +13 -0
  85. package/src/config/config.default.ts +74 -0
  86. package/src/index.ts +3 -0
  87. package/src/lib/day_rotator.ts +91 -0
  88. package/src/lib/hour_rotator.ts +44 -0
  89. package/src/lib/rotator.ts +88 -0
  90. package/src/lib/size_rotator.ts +67 -0
  91. package/src/lib/utils.ts +26 -0
  92. package/src/types.ts +15 -0
  93. package/src/typings/index.d.ts +4 -0
@@ -0,0 +1,74 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs/promises';
3
+ import { exists } from 'utility';
4
+ import moment from 'moment';
5
+ import { EggCore } from '@eggjs/core';
6
+ import { walkLoggerFile } from '../../lib/utils.js';
7
+
8
+ // clean all xxx.log.YYYY-MM-DD before expired date.
9
+ export default (app: EggCore) => ({
10
+ schedule: {
11
+ type: 'worker', // only one worker run this task
12
+ cron: '0 0 * * *', // run every day at 00:00
13
+ },
14
+
15
+ async task() {
16
+ const logger = app.coreLogger;
17
+ const logDirs = new Set<string>();
18
+ const loggerFiles = walkLoggerFile(app.loggers);
19
+ loggerFiles.forEach(file => {
20
+ const logDir = path.dirname(file);
21
+ logDirs.add(logDir);
22
+ });
23
+ const maxDays = app.config.logrotator.maxDays;
24
+ if (maxDays && maxDays > 0) {
25
+ try {
26
+ const tasks = Array.from(logDirs, logDir => removeExpiredLogFiles(logDir, maxDays, logger));
27
+ await Promise.all(tasks);
28
+ } catch (err) {
29
+ logger.error(err);
30
+ }
31
+ }
32
+
33
+ logger.info('[@eggjs/logrotator] clean all log before %s days', maxDays);
34
+ },
35
+ });
36
+
37
+ // remove expired log files: xxx.log.YYYY-MM-DD
38
+ async function removeExpiredLogFiles(logDir: string, maxDays: number, logger: EggCore['coreLogger']) {
39
+ // ignore not exists dir
40
+ const stat = await exists(logDir);
41
+ if (!stat) {
42
+ logger.warn(`[@eggjs/logrotator] logDir ${logDir} not exists`);
43
+ return;
44
+ }
45
+
46
+ const files = await fs.readdir(logDir);
47
+ const expiredDate = moment().subtract(maxDays, 'days').startOf('date');
48
+ const names = files.filter(file => {
49
+ const name = path.extname(file).substring(1);
50
+ if (!/^\d{4}\-\d{2}\-\d{2}/.test(name)) {
51
+ return false;
52
+ }
53
+ const date = moment(name, 'YYYY-MM-DD').startOf('date');
54
+ if (!date.isValid()) {
55
+ return false;
56
+ }
57
+ return date.isBefore(expiredDate);
58
+ });
59
+ if (names.length === 0) {
60
+ return;
61
+ }
62
+
63
+ logger.info(`[@eggjs/logrotator] start remove ${logDir} files: ${names.join(', ')}`);
64
+
65
+ await Promise.all(names.map(async name => {
66
+ const logFile = path.join(logDir, name);
67
+ try {
68
+ await fs.unlink(logFile);
69
+ } catch (err: any) {
70
+ err.message = `[@eggjs/logrotator] remove logFile ${logFile} error, ${err.message}`;
71
+ logger.error(err);
72
+ }
73
+ }));
74
+ }
@@ -0,0 +1,18 @@
1
+ import { EggCore } from '@eggjs/core';
2
+ import { DayRotator } from '../../lib/day_rotator.js';
3
+
4
+ export default (app: EggCore) => {
5
+ const rotator = new DayRotator({ app });
6
+
7
+ return {
8
+ schedule: {
9
+ type: 'worker', // only one worker run this task
10
+ cron: '1 0 0 * * *', // run every day at 00:00
11
+ disable: app.config.logrotator.disableRotateByDay,
12
+ },
13
+
14
+ async task() {
15
+ await rotator.rotate();
16
+ },
17
+ };
18
+ };
@@ -0,0 +1,19 @@
1
+ import { EggCore } from '@eggjs/core';
2
+ import { HourRotator } from '../../lib/hour_rotator.js';
3
+
4
+ export default (app: EggCore) => {
5
+ const rotator = new HourRotator({ app });
6
+
7
+ return {
8
+ schedule: {
9
+ type: 'worker', // only one worker run this task
10
+ cron: '1 * * * *', // run every hour at 01
11
+ disable: (app.config.logrotator.filesRotateByHour || []).length === 0,
12
+ },
13
+
14
+ async task() {
15
+ await rotator.rotate();
16
+ },
17
+
18
+ };
19
+ };
@@ -0,0 +1,18 @@
1
+ import { EggCore } from '@eggjs/core';
2
+ import { SizeRotator } from '../../lib/size_rotator.js';
3
+
4
+ export default (app: EggCore) => {
5
+ const rotator = new SizeRotator({ app });
6
+
7
+ return {
8
+ schedule: {
9
+ type: 'worker',
10
+ interval: app.config.logrotator.rotateDuration,
11
+ disable: (app.config.logrotator.filesRotateBySize || []).length === 0,
12
+ },
13
+
14
+ async task() {
15
+ await rotator.rotate();
16
+ },
17
+ };
18
+ };
package/src/app.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { Boot } from './boot.js';
2
+
3
+ export default Boot;
package/src/boot.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { EggCore, ILifecycleBoot } from '@eggjs/core';
2
+
3
+ export class Boot implements ILifecycleBoot {
4
+ constructor(private readonly app: EggCore) {}
5
+
6
+ async didLoad() {
7
+ // reload logger to new fd after rotating
8
+ this.app.messenger.on('log-reload', () => {
9
+ this.app.loggers.reload();
10
+ this.app.coreLogger.info('[@eggjs/logrotator] %s logger reload: got log-reload message', this.app.type);
11
+ });
12
+ }
13
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * logrotator options
3
+ * @member Config#logrotator
4
+ */
5
+ export interface LogrotatorConfig {
6
+ /**
7
+ * Disable rotate by day
8
+ *
9
+ * Default: `false`
10
+ */
11
+ disableRotateByDay: boolean;
12
+ /**
13
+ * List of files that will be rotated by hour
14
+ *
15
+ * Default: `null`
16
+ */
17
+ filesRotateByHour: string[] | null;
18
+ /**
19
+ * Hour delimiter
20
+ *
21
+ * Default: `-`
22
+ */
23
+ hourDelimiter: string;
24
+ /**
25
+ * List of files that will be rotated by size
26
+ *
27
+ * Default: `null`
28
+ */
29
+ filesRotateBySize: string[] | null;
30
+ /**
31
+ * Max file size to judge if any file need rotate
32
+ *
33
+ * Default: `50 * 1024 * 1024`
34
+ */
35
+ maxFileSize: number;
36
+ /**
37
+ * Max files to keep
38
+ *
39
+ * Default: `10`
40
+ */
41
+ maxFiles: number;
42
+ /**
43
+ * Time interval to judge if any file need rotate
44
+ *
45
+ * Default: `60000`
46
+ */
47
+ rotateDuration: number;
48
+ /**
49
+ * Max days to keep log files, set `0` to keep all logs.
50
+ *
51
+ * Default: `31`
52
+ */
53
+ maxDays: number;
54
+ /**
55
+ * Enable gzip compression for rotated files
56
+ *
57
+ * Default: `false`
58
+ */
59
+ gzip: boolean;
60
+ }
61
+
62
+ export default {
63
+ logrotator: {
64
+ disableRotateByDay: false,
65
+ filesRotateByHour: null,
66
+ hourDelimiter: '-',
67
+ filesRotateBySize: null,
68
+ maxFileSize: 50 * 1024 * 1024,
69
+ maxFiles: 10,
70
+ rotateDuration: 60000,
71
+ maxDays: 31,
72
+ gzip: false,
73
+ } as LogrotatorConfig,
74
+ };
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ import './types.js';
2
+
3
+ export * from './lib/rotator.js';
@@ -0,0 +1,91 @@
1
+ import path from 'node:path';
2
+ import moment from 'moment';
3
+ import fs from 'node:fs/promises';
4
+ import { debuglog } from 'node:util';
5
+ import { exists } from 'utility';
6
+ import { LogRotator, RotateFile, RotatorOptions } from './rotator.js';
7
+ import { walkLoggerFile } from './utils.js';
8
+
9
+ const debug = debuglog('@eggjs/logrotator/lib/day_rotator');
10
+
11
+ // rotate log by day
12
+ // rename from foo.log to foo.log.YYYY-MM-DD
13
+ export class DayRotator extends LogRotator {
14
+ private filesRotateBySize: string[];
15
+ private filesRotateByHour: string[];
16
+
17
+ constructor(options: RotatorOptions) {
18
+ super(options);
19
+ this.filesRotateBySize = this.app.config.logrotator.filesRotateBySize || [];
20
+ this.filesRotateByHour = this.app.config.logrotator.filesRotateByHour || [];
21
+ }
22
+
23
+ async getRotateFiles() {
24
+ const files = new Map<string, RotateFile>();
25
+ const logDir = this.app.config.logger.dir;
26
+ const loggers = this.app.loggers;
27
+ const loggerFiles = walkLoggerFile(loggers);
28
+ loggerFiles.forEach(file => {
29
+ // support relative path
30
+ if (!path.isAbsolute(file)) {
31
+ file = path.join(logDir, file);
32
+ }
33
+ this._setFile(file, files);
34
+ });
35
+
36
+ // Should rotate agent log, because schedule is running under app worker,
37
+ // agent log is the only difference between app worker and agent worker.
38
+ // - app worker -> egg-web.log
39
+ // - agent worker -> egg-agent.log
40
+ const agentLogName = this.app.config.logger.agentLogName;
41
+ this._setFile(path.join(logDir, agentLogName), files);
42
+
43
+ // rotateLogDirs is deprecated
44
+ const rotateLogDirs = this.app.config.logger.rotateLogDirs;
45
+ if (rotateLogDirs && rotateLogDirs.length > 0) {
46
+ this.app.deprecate('[egg-logrotator] Do not use app.config.logger.rotateLogDirs, only rotate core loggers and custom loggers');
47
+
48
+ for (const dir of rotateLogDirs) {
49
+ const stat = await exists(dir);
50
+ if (!stat) continue;
51
+
52
+ try {
53
+ const names = await fs.readdir(dir);
54
+ for (const name of names) {
55
+ if (!name.endsWith('.log')) {
56
+ continue;
57
+ }
58
+ this._setFile(path.join(dir, name), files);
59
+ }
60
+ } catch (err) {
61
+ this.logger.error(err);
62
+ }
63
+ }
64
+ }
65
+
66
+ return files;
67
+ }
68
+
69
+ _setFile(srcPath: string, files: Map<string, RotateFile>) {
70
+ // don't rotate logPath in filesRotateBySize
71
+ if (this.filesRotateBySize.indexOf(srcPath) > -1) {
72
+ return;
73
+ }
74
+
75
+ // don't rotate logPath in filesRotateByHour
76
+ if (this.filesRotateByHour.indexOf(srcPath) > -1) {
77
+ return;
78
+ }
79
+
80
+ if (!files.has(srcPath)) {
81
+ const ext = this.app.config.logrotator.gzip === true ? '.gz' : '';
82
+ // allow 2 minutes deviation
83
+ const targetPath = srcPath + moment()
84
+ .subtract(23, 'hours')
85
+ .subtract(58, 'minutes')
86
+ .format('.YYYY-MM-DD') + ext;
87
+ debug('set file %s => %s', srcPath, targetPath);
88
+ files.set(srcPath, { srcPath, targetPath });
89
+ }
90
+ }
91
+ }
@@ -0,0 +1,44 @@
1
+ import moment from 'moment';
2
+ import path from 'node:path';
3
+ import { debuglog } from 'node:util';
4
+ import { exists } from 'utility';
5
+ import { LogRotator, RotateFile } from './rotator.js';
6
+
7
+ const debug = debuglog('@eggjs/logrotator/lib/hour_rotator');
8
+
9
+ // rotate log by hour
10
+ // rename from foo.log to foo.log.YYYY-MM-DD-HH
11
+ export class HourRotator extends LogRotator {
12
+ async getRotateFiles() {
13
+ const files = new Map<string, RotateFile>();
14
+ const logDir = this.app.config.logger.dir;
15
+ const filesRotateByHour = this.app.config.logrotator.filesRotateByHour || [];
16
+
17
+ for (let logPath of filesRotateByHour) {
18
+ // support relative path
19
+ if (!path.isAbsolute(logPath)) {
20
+ logPath = path.join(logDir, logPath);
21
+ }
22
+ const stat = await exists(logPath);
23
+ if (!stat) {
24
+ continue;
25
+ }
26
+ this._setFile(logPath, files);
27
+ }
28
+
29
+ return files;
30
+ }
31
+
32
+ get hourDelimiter() {
33
+ return this.app.config.logrotator.hourDelimiter;
34
+ }
35
+
36
+ _setFile(srcPath: string, files: Map<string, RotateFile>) {
37
+ if (!files.has(srcPath)) {
38
+ const ext = this.app.config.logrotator.gzip === true ? '.gz' : '';
39
+ const targetPath = srcPath + moment().subtract(1, 'hours').format(`.YYYY-MM-DD${this.hourDelimiter}HH`) + ext;
40
+ debug('set file %s => %s', srcPath, targetPath);
41
+ files.set(srcPath, { srcPath, targetPath });
42
+ }
43
+ }
44
+ }
@@ -0,0 +1,88 @@
1
+ import assert from 'node:assert';
2
+ import { createWriteStream, createReadStream } from 'node:fs';
3
+ import fs from 'node:fs/promises';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import { createGzip } from 'node:zlib';
6
+ import { debuglog } from 'node:util';
7
+ import { exists } from 'utility';
8
+ import { EggCore } from '@eggjs/core';
9
+
10
+ const debug = debuglog('@eggjs/logrotator/lib/rotator');
11
+
12
+ export interface RotatorOptions {
13
+ app: EggCore;
14
+ }
15
+
16
+ export interface RotateFile {
17
+ srcPath: string;
18
+ targetPath: string;
19
+ }
20
+
21
+ export abstract class LogRotator {
22
+ protected readonly options: RotatorOptions;
23
+ protected readonly app: EggCore;
24
+ protected readonly logger: EggCore['coreLogger'];
25
+
26
+ constructor(options: RotatorOptions) {
27
+ this.options = options;
28
+ assert(this.options.app, 'options.app is required');
29
+ this.app = this.options.app;
30
+ this.logger = this.app.coreLogger;
31
+ }
32
+
33
+ abstract getRotateFiles(): Promise<Map<string, RotateFile>>;
34
+
35
+ async rotate() {
36
+ const files = await this.getRotateFiles();
37
+ assert(files instanceof Map, 'getRotateFiles should return a Map');
38
+ const rotatedFiles: string[] = [];
39
+ for (const file of files.values()) {
40
+ try {
41
+ debug('rename from %s to %s', file.srcPath, file.targetPath);
42
+ await renameOrDelete(file.srcPath, file.targetPath, this.app.config.logrotator.gzip);
43
+ rotatedFiles.push(`${file.srcPath} -> ${file.targetPath}`);
44
+ } catch (err: any) {
45
+ err.message = `[@eggjs/logrotator] rename ${file.srcPath}, found exception: ` + err.message;
46
+ this.logger.error(err);
47
+ }
48
+ }
49
+
50
+ if (rotatedFiles.length) {
51
+ // tell every one to reload logger
52
+ this.logger.info('[@eggjs/logrotator] broadcast log-reload');
53
+ this.app.messenger.sendToApp('log-reload');
54
+ this.app.messenger.sendToAgent('log-reload');
55
+ }
56
+
57
+ this.logger.info('[@eggjs/logrotator] rotate files success by %s, files %j',
58
+ this.constructor.name, rotatedFiles);
59
+ }
60
+ }
61
+
62
+ // rename from srcPath to targetPath, for example foo.log.1 > foo.log.2
63
+ // if gzip is true, then use gzip to compress the file, and delete the src file, for example foo.log.1 -> foo.log.2.gz
64
+ async function renameOrDelete(srcPath: string, targetPath: string, gzip: boolean) {
65
+ if (srcPath === targetPath) {
66
+ return;
67
+ }
68
+ const srcExists = await exists(srcPath);
69
+ if (!srcExists) {
70
+ return;
71
+ }
72
+ const targetExists = await exists(targetPath);
73
+ // if target file exists, then throw
74
+ // because the target file always be renamed first.
75
+ if (targetExists) {
76
+ const err = new Error(`targetFile ${targetPath} exists!!!`);
77
+ throw err;
78
+ }
79
+ // if gzip is true, then use gzip
80
+ if (gzip === true) {
81
+ const tmpPath = `${targetPath}.tmp`;
82
+ await fs.rename(srcPath, tmpPath);
83
+ await pipeline(createReadStream(tmpPath), createGzip(), createWriteStream(targetPath));
84
+ await fs.unlink(tmpPath);
85
+ } else {
86
+ await fs.rename(srcPath, targetPath);
87
+ }
88
+ }
@@ -0,0 +1,67 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { debuglog } from 'node:util';
4
+ import { exists } from 'utility';
5
+ import { LogRotator, RotateFile } from './rotator.js';
6
+
7
+ const debug = debuglog('@eggjs/logrotator/lib/size_rotator');
8
+
9
+ // rotate log by size, if the size of file over maxFileSize,
10
+ // it will rename from foo.log to foo.log.1
11
+ // if foo.log.1 exists, foo.log.1 will rename to foo.log.2
12
+ export class SizeRotator extends LogRotator {
13
+ async getRotateFiles() {
14
+ const files = new Map<string, RotateFile>();
15
+ const logDir = this.app.config.logger.dir;
16
+ const filesRotateBySize = this.app.config.logrotator.filesRotateBySize || [];
17
+ const maxFileSize = this.app.config.logrotator.maxFileSize;
18
+ const maxFiles = this.app.config.logrotator.maxFiles;
19
+ for (let logPath of filesRotateBySize) {
20
+ // support relative path
21
+ if (!path.isAbsolute(logPath)) {
22
+ logPath = path.join(logDir, logPath);
23
+ }
24
+ const stat = await exists(logPath);
25
+ if (!stat) {
26
+ continue;
27
+ }
28
+ const size = stat.size;
29
+ try {
30
+ if (size >= maxFileSize) {
31
+ this.logger.info(`[@eggjs/logrotator] file ${logPath} reach the maximum file size, current size: ${size}, max size: ${maxFileSize}`);
32
+ // delete max log file if exists, otherwise will throw when rename
33
+ const maxFileName = `${logPath}.${maxFiles}`;
34
+ const stat = await exists(maxFileName);
35
+ if (stat) {
36
+ await fs.unlink(maxFileName);
37
+ this.logger.info(`[@eggjs/logrotator] delete max log file ${maxFileName}`);
38
+ }
39
+ this._setFile(logPath, files);
40
+ }
41
+ } catch (err: any) {
42
+ err.message = '[@eggjs/logrotator] ' + err.message;
43
+ this.logger.error(err);
44
+ }
45
+ }
46
+ return files;
47
+ }
48
+
49
+ _setFile(logPath: string, files: Map<string, RotateFile>) {
50
+ const maxFiles = this.app.config.logrotator.maxFiles;
51
+ if (files.has(logPath)) {
52
+ return;
53
+ }
54
+ const ext = this.app.config.logrotator.gzip === true ? '.gz' : '';
55
+ // foo.log.2 -> foo.log.3
56
+ // foo.log.1 -> foo.log.2
57
+ for (let i = maxFiles - 1; i >= 1; i--) {
58
+ const srcPath = `${logPath}.${i}`;
59
+ const targetPath = `${logPath}.${i + 1}${ext}`;
60
+ debug('set file %s => %s', srcPath, targetPath);
61
+ files.set(srcPath, { srcPath, targetPath });
62
+ }
63
+ // foo.log -> foo.log.1
64
+ debug('set file %s => %s', logPath, `${logPath}.1`);
65
+ files.set(logPath, { srcPath: logPath, targetPath: `${logPath}.1${ext}` });
66
+ }
67
+ }
@@ -0,0 +1,26 @@
1
+ interface LoggerTransport {
2
+ options: {
3
+ file: string;
4
+ };
5
+ }
6
+
7
+ /**
8
+ * Walk all logger files from loggers
9
+ * @param loggers - The loggers to walk
10
+ */
11
+ export function walkLoggerFile(loggers: Record<string, Map<string, LoggerTransport>>) {
12
+ const files: string[] = [];
13
+ for (const key in loggers) {
14
+ if (!loggers.hasOwnProperty(key)) {
15
+ continue;
16
+ }
17
+ const registeredLogger = loggers[key];
18
+ for (const transport of registeredLogger.values()) {
19
+ const file = transport.options.file;
20
+ if (file) {
21
+ files.push(file);
22
+ }
23
+ }
24
+ }
25
+ return files;
26
+ }
package/src/types.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { LogrotatorConfig } from './config/config.default.js';
2
+ import type { LogRotator } from './lib/rotator.js';
3
+
4
+ export type { LogrotatorConfig };
5
+
6
+ declare module '@eggjs/core' {
7
+ // add EggAppConfig overrides types
8
+ interface EggAppConfig {
9
+ logrotator: LogrotatorConfig;
10
+ }
11
+
12
+ interface EggCore {
13
+ LogRotator: typeof LogRotator;
14
+ }
15
+ }
@@ -0,0 +1,4 @@
1
+ // make sure to import egg typings and let typescript know about it
2
+ // @see https://github.com/whxaxes/blog/issues/11
3
+ // and https://www.typescriptlang.org/docs/handbook/declaration-merging.html
4
+ import 'egg';