forked from baryon/tracer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdailyfile.js
79 lines (70 loc) · 2.71 KB
/
dailyfile.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
70
71
72
73
74
75
76
77
78
79
"use strict";
var fs = require('fs'), dateFormat = require('dateformat'), tinytim = require('tinytim'), utils = require('./utils'), spawn = require('child_process').spawn, spawnSync = require('child_process').spawnSync;
var path = require('path');
module.exports = function (conf) {
var _conf = {
root: '.',
logPathFormat: '{{root}}/{{prefix}}.{{date}}.log',
splitFormat: 'yyyymmdd',
allLogsFileName: false,
maxLogFiles: 10
};
_conf = utils.union(_conf, [conf]);
function LogFile(prefix, date) {
this.date = date;
this.path = tinytim.tim(_conf.logPathFormat, {root: _conf.root, prefix: prefix, date: date});
spawnSync('mkdir', ['-p', _conf.root]);
this.stream = fs.createWriteStream(this.path, {
flags: "a",
encoding: "utf8",
mode: parseInt('0644', 8)
// When engines node >= 4.0.0, following notation will be better:
//mode: 0o644
});
}
LogFile.prototype.write = function (str) {
this.stream.write(str + "\n");
};
LogFile.prototype.destroy = function () {
if (this.stream) {
this.stream.end();
this.stream.destroySoon();
this.stream = null;
}
};
var _logMap = {};
function _push2File(str, title) {
var logFile = _logMap[title], now = dateFormat(new Date(), _conf.splitFormat);
if (logFile && logFile.date != now) {
logFile.destroy();
logFile = null;
}
if (!logFile) {
logFile = _logMap[title] = new LogFile(title, now);
spawn('find', [_conf.root, '-type', 'f', '-name', '*.log', '-mtime', '+' + _conf.maxLogFiles, '-exec', 'rm', '{}', '\;']);
}
logFile.write(str);
if (_conf.allLogsFileName) {
var allLogFile = _logMap.allLogFile, now = dateFormat(new Date(), _conf.splitFormat);
if (allLogFile && allLogFile.date != now) {
allLogFile.destroy();
allLogFile = null;
}
if (!allLogFile) {
allLogFile = _logMap.allLogFile = new LogFile(_conf.allLogsFileName, now);
spawn('find', ['./', '-type', 'f', '-name', '*.log', '-mtime', '+' + _conf.maxLogFiles, '-exec', 'rm', '{}', '\;']);
}
allLogFile.write(str);
}
}
function dailyFileTransport(data) {
_push2File(data.output, data.title);
}
if (conf.transport) {
conf.transport = Array.isArray(conf.transport) ? conf.transport : [conf.transport];
conf.transport.push(dailyFileTransport)
} else {
conf.transport = [dailyFileTransport];
}
return require('./console')(conf);
};