ironlog 0.2.7

A web logger for multi-node system logging
Documentation
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
<!DOCTYPE html>
<html lang="en">

<script src="/resources/jquery.min.js"></script>
<script src="/resources/jquery-ui.min.js"></script>
<link rel="stylesheet" href="/resources/jquery-ui.css">


<head>
    <meta charset="UTF-8">
    <title>Log Viewer</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <!-- Dark Mode Toggle Switch -->
    <div id="darkModeToggle">
        <label class="dark-mode-label">
            <span class="label-text">Dark Mode</span>
            <input type="checkbox" id="darkModeCheckbox">
            <span class="slider"></span>
        </label>
    </div>

    <!-- Sidebar -->
    <div id="sidebar">
        <h1>Available Hashes</h1>
        <ul id="hashes"></ul>
    </div>

    <!-- Main Content -->
    <div id="main">
        <div style="display: flex; align-items: center;">
            <h2 style="margin-right: 10px;">Log Levels</h2>
            <div class="separator"></div>
            <div id="levels">
                <span class="badge INFO selected" data-level="INFO">INFO</span>
                <span class="badge WARN selected" data-level="WARN">WARN</span>
                <span class="badge ERROR selected" data-level="ERROR">ERROR</span>
                <span class="badge DEBUG selected" data-level="DEBUG">DEBUG</span>
            </div>
        </div>

        <div id="utilityContainer">
            <div id="timeInputs">
                <label for="startTime">Start Time:</label>
                <input type="datetime-local" id="startTime" name="startTime">
                <label for="endTime">End Time:</label>
                <input type="datetime-local" id="endTime" name="endTime">
            </div>
        </div>

        <!-- Dump Logs Button -->
        <div id="utilityContainer">
            <div style="display: flex; align-items: center;">
                <button id="dumpButton">Download Visible Logs</button>
                <button id="copyButton">Copy Visible Logs</button>
                <label for="logCountInput" style="margin-right: 10px;">Logs to fetch:</label>
                <input type="number" id="logCountInput" value="100" min="1">
            </div>
        </div>
        
        <!-- Logs Header with Search Bar -->
        <div id="utilityContainer">
            <div style="display: flex; align-items: center;">
                <input type="text" id="searchInput" placeholder="Search logs..." style="height: 1.5em; padding: 0.2em;"/>
            </div>
        </div>


        <table id="logs-table">
            <thead>
                <tr>
                    <th class="hash-column">Hash</th>
                    <th class="timestamp-column">Timestamp</th>
                    <th class="level-column">Level</th>
                    <th>Message</th>
                </tr>
            </thead>
            <tbody id="logs"></tbody>
        </table>
    </div>
<!-- ... (HTML code remains the same up to the script tag) -->

<script>
    // JavaScript code updated to add 24 hours on either end of the date range
    const logsElement = document.getElementById('logs');
    const hashesList = document.getElementById('hashes');
    const dumpButton = document.getElementById('dumpButton');
    const searchInput = document.getElementById('searchInput');
    const copyButton = document.getElementById('copyButton');

    let selectedHashes = new Set();
    let selectedLevels = new Set(['INFO', 'WARN', 'ERROR', 'DEBUG']);
    let hashColors = {};

    function getPastelColor(hashString) {
        let hash = 0;
        for (let i = 0; i < hashString.length; i++) {
            const char = hashString.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash;
        }

        const hue = Math.abs(hash % 360);
        const saturation = 65 + (hash % 20);
        const lightness = 55 + (hash % 15);

        return `hsla(${hue}, ${saturation}%, ${lightness}%, 0.9)`;
    }

    function fetchHashes() {
        fetch('/api/hashes')
            .then(response => response.json())
            .then(hashes => {
                hashesList.innerHTML = '';
                hashes.forEach(hash => {
                    if (!hashColors[hash]) {
                        hashColors[hash] = getPastelColor(hash);
                    }

                    const li = document.createElement('li');
                    li.innerHTML = `
                        <span class="hash-badge" style="background-color: ${hashColors[hash]};">&nbsp;</span>
                        <span class="hash-text">${hash}</span>
                    `;

                    if (selectedHashes.has(hash)) {
                        li.classList.add('selected');
                    }

                    li.onclick = () => {
                        toggleHashSelection(hash, li);
                    };
                    hashesList.appendChild(li);
                });
            });
    }

    function toggleHashSelection(hash, element) {
        if (selectedHashes.has(hash)) {
            selectedHashes.delete(hash);
            element.classList.remove('selected');
        } else {
            selectedHashes.add(hash);
            element.classList.add('selected');
        }
        fetchLogs();
    }

    // Set up level filters
    document.querySelectorAll('#levels .badge').forEach(badge => {
        const level = badge.getAttribute('data-level');

        badge.onclick = () => {
            if (selectedLevels.has(level)) {
                selectedLevels.delete(level);
                badge.classList.remove('selected');
            } else {
                selectedLevels.add(level);
                badge.classList.add('selected');
            }
            fetchLogs();
        };
    });
    function fetchLogs() {
    if (selectedHashes.size === 0) {
        logsElement.innerHTML = '<tr><td colspan="4">No hashes selected.</td></tr>';
        return;
    }

    const logCount = parseInt(document.getElementById('logCountInput').value) || 100;

    const startTimeInput = $("#startTime").val();
    const endTimeInput = $("#endTime").val();

    // Adjust time strings to include seconds if necessary
    const startTimeStr = startTimeInput.length === 16 ? startTimeInput + ':00' : startTimeInput;
    const endTimeStr = endTimeInput.length === 16 ? endTimeInput + ':00' : endTimeInput;

    // Create Date objects
    const startTime = new Date(startTimeStr);
    const endTime = new Date(endTimeStr);

    // Adjust times to add 24 hours on either end
    const adjustedStartTime = new Date(startTime.getTime() - 24 * 60 * 60 * 1000);
    const adjustedEndTime = new Date(endTime.getTime() + 24 * 60 * 60 * 1000);

    // Convert back to ISO strings
    const adjustedStartTimeStr = adjustedStartTime.toISOString().slice(0, 19);
    const adjustedEndTimeStr = adjustedEndTime.toISOString().slice(0, 19);

    const promises = [];
    selectedHashes.forEach(hash => {
        const url = `/api/logs/${hash}?count=${logCount}&start=${encodeURIComponent(adjustedStartTimeStr)}&end=${encodeURIComponent(adjustedEndTimeStr)}`;
        const promise = fetch(url)
            .then(response => response.json())
            .then(logs => logs);
        promises.push(promise);
    });

    Promise.all(promises).then(results => {
        logsElement.innerHTML = '';
        const allLogs = results.flat();

        const searchQuery = searchInput.value.toLowerCase();

        const filteredLogs = allLogs.filter(log =>
            (selectedLevels.size === 0 || selectedLevels.has(log.level)) &&
            (!searchQuery || log.message.toLowerCase().includes(searchQuery))
        );

        // **Add this sorting step**
        // Sort logs by timestamp in ascending order
        //filteredLogs.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

        // If you prefer descending order (most recent first), use:
        filteredLogs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

        filteredLogs.forEach(log => {
            const row = document.createElement('tr');

            const date = new Date(log.timestamp);
            const formattedTimestamp = date.toLocaleString(undefined, {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });

            row.innerHTML = `
                <td class="hash-column">
                    <span class="hash-badge-table" style="background-color: ${hashColors[log.hash]};">${log.hash}</span>
                </td>
                <td class="timestamp-column">${formattedTimestamp}</td>
                <td class="level-column">
                    <span class="level-label level-${log.level}">${log.level}</span>
                </td>
                <td>${log.message}</td>
            `;
            logsElement.appendChild(row);
        });
    });
}


    // Copy visible logs to clipboard
    copyButton.onclick = () => {
        const rows = logsElement.querySelectorAll('tr');
        if (rows.length === 0) {
            alert('No logs to copy.');
            return;
        }

        let clipboardContent = 'Hash\tLevel\tTimestamp\tMessage\n';

        rows.forEach(row => {
            const cols = row.querySelectorAll('td');
            const data = [];
            cols.forEach(col => {
                data.push(col.textContent.trim());
            });
            clipboardContent += data.join('\t') + '\n';
        });

        navigator.clipboard.writeText(clipboardContent).then(() => {
            alert('Logs copied to clipboard.');
        }, () => {
            alert('Failed to copy logs to clipboard.');
        });
    };

    // Dump visible logs to a file
    dumpButton.onclick = () => {
        const rows = logsElement.querySelectorAll('tr');
        if (rows.length === 0) {
            alert('No logs to download.');
            return;
        }

        let csvContent = 'Hash,Level,Timestamp,Message\n';

        rows.forEach(row => {
            const cols = row.querySelectorAll('td');
            const data = [];
            cols.forEach(col => data.push('"' + col.innerText.replace(/"/g, '""') + '"'));
            csvContent += data.join(',') + '\n';
        });

        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', 'logs.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    // Handle search input
    searchInput.addEventListener('input', () => {
        fetchLogs();
    });

    const darkModeCheckbox = document.getElementById('darkModeCheckbox');
    const bodyElement = document.body;

    // Load dark mode preference from localStorage
    if (localStorage.getItem('darkMode') === 'enabled') {
        bodyElement.classList.add('dark-mode');
        darkModeCheckbox.checked = true;
    }

    darkModeCheckbox.addEventListener('change', () => {
        if (darkModeCheckbox.checked) {
            bodyElement.classList.add('dark-mode');
            localStorage.setItem('darkMode', 'enabled');
        } else {
            bodyElement.classList.remove('dark-mode');
            localStorage.setItem('darkMode', 'disabled');
        }
    });

    // Fetch and set the date range for the inputs
    async function fetchDateRange() {
        try {
            const response = await fetch('/api/date_range');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();

            if (!data.min_date || !data.max_date) {
                throw new Error('Server returned invalid date range');
            }

            let minDate = new Date(data.min_date);
            let maxDate = new Date(data.max_date);

            if (isNaN(minDate.getTime()) || isNaN(maxDate.getTime())) {
                throw new Error('Invalid date parsed from server data');
            }

            // Adjust minDate if the range is too narrow
            if (maxDate.getTime() - minDate.getTime() < 3600000) {
                minDate = new Date(maxDate.getTime() - 24 * 3600000);
                console.warn('Date range too narrow, adjusting minDate to 24 hours before maxDate');
            }

            const minDateStr = minDate.toISOString().slice(0, 16);
            const maxDateStr = maxDate.toISOString().slice(0, 16);

            // Set min and max attributes
            $("#startTime").attr('min', minDateStr);
            $("#startTime").attr('max', maxDateStr);
            $("#endTime").attr('min', minDateStr);
            $("#endTime").attr('max', maxDateStr);

            // Set initial values if not already set
            if (!$("#startTime").val()) {
                $("#startTime").val(minDateStr);
            }
            if (!$("#endTime").val()) {
                $("#endTime").val(maxDateStr);
            }

        } catch (error) {
            console.error('Error in fetchDateRange:', error);
            const fallbackMinDate = new Date(Date.now() - 60 * 1000);
            const fallbackMaxDate = new Date();
            const minDateStr = fallbackMinDate.toISOString().slice(0, 16);
            const maxDateStr = fallbackMaxDate.toISOString().slice(0, 16);

            $("#startTime").attr('min', minDateStr);
            $("#startTime").attr('max', maxDateStr);
            $("#endTime").attr('min', minDateStr);
            $("#endTime").attr('max', maxDateStr);

            if (!$("#startTime").val()) {
                $("#startTime").val(minDateStr);
            }
            if (!$("#endTime").val()) {
                $("#endTime").val(maxDateStr);
            }
        }
    }

    // Initialize date inputs
    $(async function () {
        await fetchDateRange();

        // Fetch logs when date inputs change
        $("#startTime, #endTime").on("change", function () {
            fetchLogs();
        });

        // Initial fetch of logs
        fetchLogs();
    });

    // Initial fetch of hashes
    fetchHashes();

    // Refresh hashes every 3 seconds
    setInterval(fetchHashes, 3000);

    // Refresh logs every 1 second
    setInterval(fetchLogs, 1000);

</script>

</body>
</html>