-
Notifications
You must be signed in to change notification settings - Fork 14
/
size_rotator.js
69 lines (61 loc) · 2.31 KB
/
size_rotator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict';
const fs = require('mz/fs');
const path = require('path');
const debug = require('debug')('egg-logrotator:size_rotator');
const Rotator = require('./rotator');
// rotate log by size, if the size of file over maxFileSize,
// it will rename from foo.log to foo.log.1
// if foo.log.1 exists, foo.log.1 will rename to foo.log.2
class SizeRotator extends Rotator {
async getRotateFiles() {
const files = new Map();
const logDir = this.app.config.logger.dir;
const filesRotateBySize = this.app.config.logrotator.filesRotateBySize || [];
const maxFileSize = this.app.config.logrotator.maxFileSize;
const maxFiles = this.app.config.logrotator.maxFiles;
for (let logPath of filesRotateBySize) {
// support relative path
if (!path.isAbsolute(logPath)) logPath = path.join(logDir, logPath);
const exists = await fs.exists(logPath);
if (!exists) {
continue;
}
try {
const stat = await fs.stat(logPath);
if (stat.size >= maxFileSize) {
this.logger.info(`[egg-logrotator] file ${logPath} reach the maximum file size, current size: ${stat.size}, max size: ${maxFileSize}`);
// delete max log file if exists, otherwise will throw when rename
const maxFileName = `${logPath}.${maxFiles}`;
const maxExists = await fs.exists(maxFileName);
if (maxExists) {
await fs.unlink(maxFileName);
}
this._setFile(logPath, files);
}
} catch (err) {
err.message = '[egg-logrotator] ' + err.message;
this.logger.error(err);
}
}
return files;
}
_setFile(logPath, files) {
const maxFiles = this.app.config.logrotator.maxFiles;
if (files.has(logPath)) {
return;
}
const ext = this.app.config.logrotator.gzip === true ? '.gz' : '';
// foo.log.2 -> foo.log.3
// foo.log.1 -> foo.log.2
for (let i = maxFiles - 1; i >= 1; i--) {
const srcPath = `${logPath}.${i}`;
const targetPath = `${logPath}.${i + 1}${ext}`;
debug('set file %s => %s', srcPath, targetPath);
files.set(srcPath, { srcPath, targetPath });
}
// foo.log -> foo.log.1
debug('set file %s => %s', logPath, `${logPath}.1`);
files.set(logPath, { srcPath: logPath, targetPath: `${logPath}.1${ext}` });
}
}
module.exports = SizeRotator;