log.js
1.91 KB
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
80
81
82
83
84
85
86
87
88
89
var fs = require('fs');
var moment = require('moment');
var helper = require('../lib/helper');
var _ = require('lodash');
/*
* parameters:
* dirname: string
* rotation: interger (ms)
*/
function log(dirname, opts) {
opts = opts || {};
this.dirname = dirname;
this.rotation = opts.rotation || 15 * 60 * 1000;
this.maxsize = opts.maxsize || 20000;
this.currentsize = 0;
this.timestamp = 0;
this.foldername = 'log/';
helper.mkdirIfNotExist(`${this.dirname}/${this.foldername}`);
};
/*
* parameters:
* data: any
*/
log.prototype.append = function(data) {
data = this.formatData(data);
this.currentsize = this.currentsize + helper.getLengthOfContent(data);
fs.appendFile(this.getDir(), data, function(err) {});
};
/*
* parameters:
* none
*/
log.prototype.getDir = function() {
var time = moment(Math.floor((+moment()) / this.rotation) * this.rotation);
this.resetCurrentSize(time.unix());
time = time.format('YYYY-MM-DDTHH-mm-ss');
var count = this.getCount();
return `${this.dirname}${this.foldername}${time}_${count}.txt`;
};
/*
* parameters:
* time_unix: string
*/
log.prototype.resetCurrentSize = function(time_unix) {
if(time_unix > this.timestamp) {
this.currentsize = 0
this.timestamp = time_unix;
}
};
/*
* parameters:
* none
*/
log.prototype.getCount = function() {
var count = Math.floor((this.currentsize / this.maxsize) + 1);
return ((count * 1e-5).toFixed(5)).split('.')[1];
};
/*
* parameters:
* data: any
*/
log.prototype.formatData = function(data) {
var date = moment().toISOString().trim();
var timestamp = moment().unix();
data = this._formatObject(data).trim();
return `${date} ${timestamp} ${data}\r\n`;
};
/*
* parameters:
* data: any
*/
log.prototype._formatObject = function(data) {
if(_.isObject(data)) {
return JSON.stringify(data);
}
if(_.isNumber(data)) {
return toString(data);
}
return data;
};
module.exports = log;