-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatchlog.js
83 lines (74 loc) · 2.62 KB
/
watchlog.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
const fs = require('fs');
const { parseLogFile } = require('./parseLogFile');
const { sendNotification } = require('./sendNotification');
let currentWatcher = null;
let startProcessPosition = 0;
let debounceTimeout = null;
/**
* Call the log update event on the main window.
* @param {object} options - The main window object.
* @param {object} options.mainWindow - The main window object.
* @param {string} options.logPath - The path to the log file.
* @param {Array} options.logEntries - The log entries to send.
*/
function callLogUpdate({ mainWindow, logPath, logEntries }) {
if ( mainWindow && !mainWindow.isDestroyed() ) {
mainWindow.webContents.send( 'log-update', { logPath, logEntries } );
}
}
/**
* Watches the log file for changes and processes new entries.
* @param {object} mainWindow - The main window object.
* @param {string} logPath - The path to the log file.
* @param {boolean} reset - Whether to reset the log position.
*/
async function watchLogFile( mainWindow, logPath, reset = false ) {
if ( !fs.existsSync( logPath ) ) {
console.error( 'Log file does not exist:', logPath );
return;
}
if ( reset ) {
startProcessPosition = 0;
mainWindow.webContents.send( 'log-reset', { logPath } );
}
// Stop watching the previous file if there is an existing watcher
if ( currentWatcher ) {
currentWatcher.close();
}
// Send initially the logs
try {
const { logEntries, lastProcessedPosition } = await parseLogFile({
logPath,
streamOptions: { start: startProcessPosition },
});
startProcessPosition = lastProcessedPosition;
callLogUpdate({mainWindow, logPath, logEntries});
} catch (error) {
console.error('Error processing log file:', error);
}
// Watch for new changes with debouncing and send notifications for
// new entries if the window is minimized
currentWatcher = fs.watch( logPath, ( eventType ) => {
if ( eventType === 'change' ) {
if ( debounceTimeout ) {
clearTimeout( debounceTimeout );
}
debounceTimeout = setTimeout(async () => {
try {
const { logEntries, lastProcessedPosition } = await parseLogFile({
logPath,
streamOptions: { start: startProcessPosition },
});
startProcessPosition = lastProcessedPosition;
callLogUpdate({mainWindow, logPath, logEntries});
if (mainWindow.isMinimized()) {
sendNotification(logEntries[logEntries.length - 1]);
}
} catch (error) {
console.error('Error processing log file:', error);
}
}, 100 );
}
});
}
module.exports = { watchLogFile };