-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.js
248 lines (212 loc) · 7.28 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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
const path = require('path');
const fs = require('fs').promises;
const util = require('util');
// Log level definitions with both console colors and clean log formats
const LOG_LEVELS = {
INFO: {
console: '\x1b[32m',
label: 'INFO',
cleanLabel: 'INFO'
},
WARN: {
console: '\x1b[33m',
label: 'WARN',
cleanLabel: 'WARNING'
},
ERROR: {
console: '\x1b[31m',
label: 'ERROR',
cleanLabel: 'ERROR'
},
DEBUG: {
console: '\x1b[36m',
label: 'DEBUG',
cleanLabel: 'DEBUG'
}
};
class Logger {
constructor() {
this.isRenderer = process.type === 'renderer';
this.logPath = '';
this.currentLogFile = '';
if (this.isRenderer) {
const { ipcRenderer } = require('electron');
this.ipc = ipcRenderer;
} else {
const { app, ipcMain } = require('electron');
this.ipc = ipcMain;
this.app = app;
this.setupMainProcess();
}
}
setupMainProcess() {
this.ipc.handle('logger-write', async (event, { type, message, data, error }) => {
const formattedMessage = this.formatLogMessage(type, message, data, error);
await this.writeToFile(formattedMessage);
});
this.initializeMain();
}
async initializeMain() {
try {
this.logPath = path.join(this.app.getPath('userData'), 'logs');
await fs.mkdir(this.logPath, { recursive: true });
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
this.currentLogFile = path.join(this.logPath, `app-${timestamp}.log`);
await this.writeInitialLogEntry();
} catch (error) {
console.error('Failed to initialize logger:', error);
}
}
async writeInitialLogEntry() {
const border = '='.repeat(80);
const startMessage = [
border,
'Log Session Started',
`Timestamp: ${new Date().toISOString()}`,
border,
''
].join('\n');
await fs.writeFile(this.currentLogFile, startMessage, 'utf8');
}
async logSystemInfo() {
if (this.isRenderer) return;
const systemInfo = [
'System Information:',
'-'.repeat(50),
`App Version: ${this.app.getVersion()}`,
`Electron: ${process.versions.electron}`,
`Chrome: ${process.versions.chrome}`,
`Node: ${process.versions.node}`,
`Platform: ${process.platform}`,
`Architecture: ${process.arch}`,
`Process Type: ${process.type}`,
`User Data Path: ${this.app.getPath('userData')}`,
'-'.repeat(50),
''
].join('\n');
await this.writeToFile(systemInfo);
}
async cleanOldLogs() {
if (this.isRenderer) return;
try {
const files = await fs.readdir(this.logPath);
const now = new Date();
for (const file of files) {
if (!file.endsWith('.log')) continue;
const filePath = path.join(this.logPath, file);
const stats = await fs.stat(filePath);
const daysOld = (now - stats.mtime) / (1000 * 60 * 60 * 24);
if (daysOld > 7) {
await fs.unlink(filePath);
}
}
} catch (error) {
console.error('Failed to clean old logs:', error);
}
}
formatLogMessage(type, message, data = null, error = null) {
const timestamp = new Date().toISOString();
let formatted = `${timestamp} ${type.padEnd(7)} [${process.type}] `;
// Handle message and data
if (typeof data !== 'undefined' && data !== null) {
if (typeof data === 'object') {
const objString = util.inspect(data, {
depth: null,
colors: false,
compact: true,
breakLength: Infinity
});
formatted += `${message} ${objString}`;
} else {
if (message.endsWith(':')) {
formatted += `${message} ${data}`;
} else {
formatted += `${message}${data}`;
}
}
} else {
formatted += message;
}
if (error) {
formatted += `\nError: ${error.message}`;
if (error.stack) {
formatted += `\nStack: ${error.stack}`;
}
}
return formatted;
}
async log(type, message, data = null, error = null) {
let finalMessage = '';
let finalData = data;
// Handle different message formats
if (typeof message === 'string' && data !== null && data !== undefined) {
finalMessage = message;
finalData = data;
} else if (typeof message === 'object' && data === null) {
finalMessage = '';
finalData = message;
} else {
finalMessage = String(message);
}
// Format the message
const fileMessage = this.formatLogMessage(type, finalMessage, finalData, error);
let consoleMessage = fileMessage;
// Add colors for console output
if (type === 'INFO') consoleMessage = `\x1b[32m${fileMessage}\x1b[0m`;
else if (type === 'WARN') consoleMessage = `\x1b[33m${fileMessage}\x1b[0m`;
else if (type === 'ERROR') consoleMessage = `\x1b[31m${fileMessage}\x1b[0m`;
else if (type === 'DEBUG') consoleMessage = `\x1b[36m${fileMessage}\x1b[0m`;
// Console output
console[type.toLowerCase()](consoleMessage);
// File output
if (this.isRenderer) {
try {
await this.ipc.invoke('logger-write', {
type,
message: finalMessage,
data: finalData,
error
});
} catch (err) {
console.error('Failed to send log to main process:', err);
}
} else {
await this.writeToFile(fileMessage);
}
}
// Convenience methods
async info(message, data = null) {
await this.log('INFO', message, data);
}
async warn(message, data = null) {
await this.log('WARN', message, data);
}
async error(message, error = null, data = null) {
if (error instanceof Error) {
await this.log('ERROR', message, data, error);
} else {
await this.log('ERROR', message, error);
}
}
async debug(message, data = null) {
await this.log('DEBUG', message, data);
}
async writeToFile(message) {
if (this.isRenderer) return;
try {
await fs.appendFile(this.currentLogFile, message + '\n', 'utf8');
} catch (error) {
console.error('Failed to write to log file:', error);
}
}
getLogPath() {
return this.currentLogFile;
}
}
let logger;
if (process.type === 'renderer') {
logger = new Logger();
} else {
logger = new Logger();
}
module.exports = logger;