-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
147 lines (122 loc) · 4.31 KB
/
index.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const fs = require('fs');
const path = require('path');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, printf, splat } = format;
const zlib = require('zlib');
class Logger {
constructor(config) {
this.logLevel = config.logLevel || 'info';
this.logFile = config.logFile || path.join(__dirname, 'logs', 'app.log');
this.maxSize = config.maxSize || 5242880; // 5MB
this.maxFiles = config.maxFiles || 5;
this.enableConsoleLogging = config.enableConsoleLogging !== undefined ? config.enableConsoleLogging : true;
this.compressLogs = config.compressLogs || false;
this.persistLogs = config.persistLogs || true;
this.logger = null;
this.initializeLogger();
this.createLogFile();
this.cleanupOldLogFiles();
}
initializeLogger() {
const logFormat = combine(
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
splat(),
printf(({ level, message, timestamp, metadata }) => `[${timestamp}] [${level.toUpperCase()}]: ${message} ${metadata ? JSON.stringify(metadata) : ''}`)
);
this.logger = createLogger({
level: this.logLevel,
format: logFormat,
transports: [
new transports.Console({
format: logFormat,
silent: !this.enableConsoleLogging,
}),
new transports.File({
filename: this.logFile,
maxsize: this.maxSize,
maxFiles: this.maxFiles,
}),
],
});
}
createLogFile() {
const logDirectory = path.dirname(this.logFile);
// Create the logs directory if it doesn't exist
if (!fs.existsSync(logDirectory)) {
fs.mkdirSync(logDirectory);
}
// Create or overwrite the log file
fs.writeFileSync(this.logFile, '');
}
cleanupOldLogFiles() {
const logDirectory = path.dirname(this.logFile);
fs.readdir(logDirectory, (err, files) => {
if (err) {
this.error(`Error cleaning up log files: ${err}`);
return;
}
const logFiles = files.filter((file) => file.startsWith('app.log'));
if (logFiles.length <= this.maxFiles) {
return;
}
const filesToDelete = logFiles.slice(0, logFiles.length - this.maxFiles);
for (const file of filesToDelete) {
const filePath = path.join(logDirectory, file);
fs.unlink(filePath, (err) => {
if (err) {
this.error(`Error deleting log file '${filePath}': ${err}`);
} else {
this.log(`Deleted log file '${filePath}'`);
}
});
}
});
}
log(message, metadata) {
this.logger.log('info', message, metadata);
this.writeToLogFile('info', message, metadata);
}
warn(message, metadata) {
this.logger.log('warn', message, metadata);
this.writeToLogFile('warn', message, metadata);
}
error(message, error, metadata) {
this.logger.log('error', message, { error, ...metadata });
this.writeToLogFile('error', message, { error, ...metadata });
}
writeToLogFile(level, message, metadata) {
const logEntry = { level, message, timestamp: new Date().toISOString(), metadata };
const logString = JSON.stringify(logEntry) + '\n';
if (this.persistLogs) {
fs.appendFileSync(this.logFile, logString);
if (this.compressLogs) {
this.compressLogFile();
}
}
}
compressLogFile() {
const compressedLogFile = `${this.logFile}.gz`;
const inputStream = fs.createReadStream(this.logFile);
const outputStream = fs.createWriteStream(compressedLogFile);
const gzip = zlib.createGzip();
inputStream.pipe(gzip).pipe(outputStream);
inputStream.on('end', () => {
fs.unlink(this.logFile, (err) => {
if (err) {
this.error(`Error deleting log file '${this.logFile}': ${err}`);
} else {
this.log(`Deleted log file '${this.logFile}'`);
}
});
});
}
getLogs(options) {
const logContents = fs.readFileSync(this.logFile, 'utf-8');
const logs = logContents.split('\n').filter((line) => line !== '').map((line) => JSON.parse(line));
if (options && options.level) {
return logs.filter((log) => log.level === options.level);
}
return logs;
}
}
module.exports = Logger;