-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog-util.js
110 lines (94 loc) · 3 KB
/
log-util.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const moment = require('moment');
const util = require('util');
const path = require('path');
const fs = require('fs-extra');
function mkdir(path) {
fs.ensureDirSync(path);
}
class LogUtil {
constructor(options) {
const opt = options || {};
this.colors = opt.colors || true;
this.compact = opt.compact || true;
this.sorted = opt.sorted === true ? true : false;
this.depth = opt.depth || null;
this.join = opt.join || ' ';
this.break = opt.break || Infinity;
this.format = opt.format || 'YYMMDD.HHmmss';
}
print() {
console.log(
moment().format(this.format),
[...arguments]
.map(v => util.inspect(v, {
maxArrayLength: null,
breakLength: this.break,
colors: this.colors,
compact: this.compact,
sorted: this.sorted,
depth: this.depth
}))
.join(this.join)
);
}
open(options, exits) {
let log = this;
let opt = options || {};
let dir = opt.dir || "logs";
let exiting = false;
let logfile = null;
let logstream = null;
let pattern = opt.pattern || 'YY-MM-DD-HH';
let last_pattern;
let count_min = opt.min || 1000;
let count = 0;
mkdir(dir);
// create file write stream
function open_file_stream() {
close_file_stream();
logfile = path.join(dir, last_pattern = moment().format(pattern));
logstream = fs.createWriteStream(logfile, {flags: 'a'});
let cur = path.join(dir, "current");
try { fs.unlinkSync(cur) } catch (e) { }
try { fs.symlinkSync(last_pattern, cur) } catch (e) { }
count = 0;
}
function close_file_stream() {
if (logstream) {
logstream.end();
logstream = null;
}
}
function emit_log() {
log.print(...arguments);
emit(...arguments);
}
function emit() {
if (exiting) {
// console.log({dir: opt.dir, exiting_skip_log: obj})
return;
}
let args = [...arguments].map(v => JSON.stringify(v));
let next_pattern = moment().format(pattern);
if (++count > count_min && next_pattern !== last_pattern) {
open_file_stream();
}
let output = [moment().format('YYMMDD-HHmmss'),...args,'\n'].join(' ');
logstream.write(output);
}
function exit() {
exiting = true;
close_file_stream();
}
open_file_stream();
if (exits) exits.push(exit);
return { emit, log: emit_log, close: close_file_stream };
}
}
module.exports = {
new: function(options) {
return new LogUtil(options);
},
class: LogUtil,
default: new LogUtil()
};