-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathlogger.js
71 lines (58 loc) · 1.59 KB
/
logger.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
'use strict';
const fs = require('node:fs');
const util = require('node:util');
const path = require('node:path');
const COLORS = {
info: '\x1b[1;37m',
debug: '\x1b[1;33m',
error: '\x1b[0;31m',
system: '\x1b[1;34m',
access: '\x1b[1;38m',
};
const DATETIME_LENGTH = 19;
class Logger {
constructor(logPath) {
this.path = logPath;
const date = new Date().toISOString().substring(0, 10);
const filePath = path.join(logPath, `${date}.log`);
this.stream = fs.createWriteStream(filePath, { flags: 'a' });
this.regexp = new RegExp(path.dirname(this.path), 'g');
}
close() {
return new Promise((resolve) => this.stream.end(resolve));
}
write(type = 'info', s) {
const now = new Date().toISOString();
const date = now.substring(0, DATETIME_LENGTH);
const color = COLORS[type];
const line = date + '\t' + s;
console.log(color + line + '\x1b[0m');
const out = line.replace(/[\n\r]\s*/g, '; ') + '\n';
this.stream.write(out);
}
log(...args) {
const msg = util.format(...args);
this.write('info', msg);
}
dir(...args) {
const msg = util.inspect(...args);
this.write('info', msg);
}
debug(...args) {
const msg = util.format(...args);
this.write('debug', msg);
}
error(...args) {
const msg = util.format(...args).replace(/[\n\r]{2,}/g, '\n');
this.write('error', msg.replace(this.regexp, ''));
}
system(...args) {
const msg = util.format(...args);
this.write('system', msg);
}
access(...args) {
const msg = util.format(...args);
this.write('access', msg);
}
}
module.exports = Logger;