-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlogger.js
More file actions
108 lines (90 loc) · 2.34 KB
/
Copy pathlogger.js
File metadata and controls
108 lines (90 loc) · 2.34 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const fs = require('fs');
const path = require('path');
const util = require('util');
const LOG_DIR = process.env.LOG_DIR || path.join(__dirname, 'logs');
const TOKEN_PATTERNS = [
/(token\s*[=:]\s*)["']?[^"'\s]+/gi,
/(authorization\s*:\s*bot\s+)[^"'\s]+/gi,
/(key=)[^&\s]+/gi,
];
let installed = false;
let currentDate = null;
let stream = null;
function getDateParts(now = new Date()) {
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function ensureLogStream() {
const date = getDateParts();
if (stream && currentDate === date) {
return stream;
}
if (stream) {
stream.end();
stream = null;
}
fs.mkdirSync(LOG_DIR, { recursive: true });
currentDate = date;
stream = fs.createWriteStream(path.join(LOG_DIR, `${date}.log`), { flags: 'a' });
return stream;
}
function redactSecrets(message) {
return TOKEN_PATTERNS.reduce(
(text, pattern) => text.replace(pattern, '$1[REDACTED]'),
message
);
}
function formatArgs(args) {
return redactSecrets(args.map((arg) => {
if (arg instanceof Error) {
return arg.stack || arg.message;
}
if (typeof arg === 'string') {
return arg;
}
return util.inspect(arg, {
depth: 6,
colors: false,
breakLength: 120,
});
}).join(' '));
}
function write(level, args) {
const line = `[${new Date().toISOString()}] [${level.toUpperCase()}] ${formatArgs(args)}\n`;
try {
ensureLogStream().write(line);
} catch (_) {
// Avoid recursive logging if filesystem logging itself fails.
}
}
function installLogger() {
if (installed) {
return;
}
installed = true;
const original = {
log: console.log.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
debug: console.debug.bind(console),
};
for (const level of Object.keys(original)) {
console[level] = (...args) => {
write(level, args);
original[level](...args);
};
}
process.on('warning', (warning) => {
write('warning', [warning]);
});
process.on('beforeExit', () => {
if (stream) {
stream.end();
}
});
console.info(`[Logger] Daily logs enabled in ${LOG_DIR}`);
}
module.exports = { installLogger };