-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudwatch_log_viewer.html
More file actions
453 lines (410 loc) · 15.3 KB
/
cloudwatch_log_viewer.html
File metadata and controls
453 lines (410 loc) · 15.3 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
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CloudWatch Log Streamer</title>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1001.0.min.js"></script>
<style>
body {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
margin: 0;
padding: 20px;
background-color: #1e1e1e;
color: #d4d4d4;
}
.container {
max-width: 1200px;
margin: 0 auto;
display: flex;
flex-direction: column;
height: 100vh;
}
.header {
margin-bottom: 20px;
flex-shrink: 0;
}
.input-group {
margin-bottom: 15px;
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
input[type="text"] {
padding: 8px;
width: 300px;
background-color: #2d2d2d;
border: 1px solid #3d3d3d;
color: #d4d4d4;
border-radius: 4px;
}
button {
padding: 8px 16px;
background-color: #0078d4;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #106ebe;
}
.log-viewer {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
background-color: #2d2d2d;
border-radius: 4px;
overflow: hidden;
}
.log-header {
padding: 10px;
background-color: #252526;
border-bottom: 1px solid #3d3d3d;
display: flex;
justify-content: space-between;
align-items: center;
}
.log-controls {
display: flex;
gap: 10px;
}
.log-container {
flex: 1;
overflow-y: auto;
padding: 10px;
scroll-behavior: smooth;
}
.log-entry {
margin: 2px 0;
padding: 4px 8px;
border-radius: 2px;
display: flex;
align-items: flex-start;
line-height: 1.4;
}
.log-entry:hover {
background-color: #323232;
}
.log-entry.selected {
background-color: #37373d;
}
.timestamp {
color: #569cd6;
margin-right: 8px;
white-space: nowrap;
}
.log-level {
padding: 2px 6px;
border-radius: 3px;
margin-right: 8px;
font-size: 0.9em;
font-weight: bold;
min-width: 60px;
text-align: center;
}
.log-content {
flex: 1;
word-break: break-word;
}
.error {
background-color: rgba(241, 76, 76, 0.1);
color: #f14c4c;
}
.warn {
background-color: rgba(204, 167, 0, 0.1);
color: #cca700;
}
.info {
background-color: rgba(106, 153, 85, 0.1);
color: #6a9955;
}
.debug {
background-color: rgba(156, 220, 254, 0.1);
color: #9cdcfe;
}
.trace {
background-color: rgba(197, 134, 192, 0.1);
color: #c586c0;
}
.status {
color: #6a9955;
margin-bottom: 10px;
}
.filter-input {
padding: 4px 8px;
background-color: #3c3c3c;
border: 1px solid #3d3d3d;
color: #d4d4d4;
border-radius: 4px;
width: 200px;
}
.json-content {
background-color: #1e1e1e;
padding: 8px;
border-radius: 4px;
margin-top: 4px;
overflow-x: auto;
}
.json-key { color: #9cdcfe; }
.json-string { color: #ce9178; }
.json-number { color: #b5cea8; }
.json-boolean { color: #569cd6; }
.json-null { color: #569cd6; }
.auto-scroll {
display: flex;
align-items: center;
gap: 5px;
color: #d4d4d4;
}
.auto-scroll input[type="checkbox"] {
margin: 0;
}
.log-count {
color: #6a9955;
font-size: 0.9em;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>CloudWatch Log Streamer</h1>
<div class="input-group">
<input type="text" id="logGroupName" placeholder="Log Group Name">
<input type="text" id="identityPoolId" placeholder="Identity Pool ID">
<button onclick="startStreaming()">Start Streaming</button>
<button onclick="stopStreaming()">Stop Streaming</button>
</div>
<div id="status" class="status"></div>
</div>
<div class="log-viewer">
<div class="log-header">
<div class="log-controls">
<input type="text" id="filterInput" class="filter-input" placeholder="Filter logs...">
<div class="auto-scroll">
<input type="checkbox" id="autoScroll" checked>
<label for="autoScroll">Auto-scroll</label>
</div>
</div>
<div class="log-count" id="logCount">0 logs</div>
</div>
<div id="logContainer" class="log-container"></div>
</div>
</div>
<script>
// Constants matching Ruby implementation
const POLL_INTERVAL = 1000; // 1 second
const MAX_STREAMS = 10;
const REGION = 'us-east-1';
const LOOKBACK_MINUTES = 5;
// State variables
let isStreaming = false;
let lastIngestedMap = {};
let cloudWatchLogs;
let cognitoClient;
let logCount = 0;
let autoScroll = true;
// Configure AWS SDK
AWS.config.region = REGION;
// Initialize UI controls
document.getElementById('autoScroll').addEventListener('change', (e) => {
autoScroll = e.target.checked;
});
document.getElementById('filterInput').addEventListener('input', (e) => {
filterLogs(e.target.value);
});
function updateStatus(message, isError = false) {
const status = document.getElementById('status');
status.textContent = message;
status.style.color = isError ? '#f14c4c' : '#6a9955';
}
function updateLogCount() {
document.getElementById('logCount').textContent = `${logCount} logs`;
}
function filterLogs(filterText) {
const logEntries = document.querySelectorAll('.log-entry');
const filterLower = filterText.toLowerCase();
logEntries.forEach(entry => {
const content = entry.textContent.toLowerCase();
entry.style.display = content.includes(filterLower) ? 'flex' : 'none';
});
}
function formatJSON(json) {
if (typeof json !== 'object') return json;
const formatted = JSON.stringify(json, null, 2);
return formatted.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
match => {
let cls = 'json-number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'json-key';
} else {
cls = 'json-string';
}
} else if (/true|false/.test(match)) {
cls = 'json-boolean';
} else if (/null/.test(match)) {
cls = 'json-null';
}
return `<span class="${cls}">${match}</span>`;
}
);
}
async function setupCognitoClient(identityPoolId) {
try {
updateStatus('Setting up Cognito authentication...');
cognitoClient = new AWS.CognitoIdentity();
const identityResponse = await cognitoClient.getId({
IdentityPoolId: identityPoolId,
Logins: {}
}).promise();
const credentialsResponse = await cognitoClient.getCredentialsForIdentity({
IdentityId: identityResponse.IdentityId,
Logins: {}
}).promise();
AWS.config.credentials = new AWS.Credentials({
accessKeyId: credentialsResponse.Credentials.AccessKeyId,
secretAccessKey: credentialsResponse.Credentials.SecretKey,
sessionToken: credentialsResponse.Credentials.SessionToken
});
cloudWatchLogs = new AWS.CloudWatchLogs();
updateStatus('Cognito authentication successful');
return true;
} catch (error) {
updateStatus(`Cognito authentication failed: ${error.message}`, true);
return false;
}
}
async function startStreaming() {
const logGroupName = document.getElementById('logGroupName').value;
const identityPoolId = document.getElementById('identityPoolId').value;
if (!logGroupName || !identityPoolId) {
updateStatus('Please enter both Log Group Name and Identity Pool ID', true);
return;
}
const authSuccess = await setupCognitoClient(identityPoolId);
if (!authSuccess) {
return;
}
try {
const data = await cloudWatchLogs.describeLogGroups({
logGroupNamePrefix: logGroupName
}).promise();
const logGroupExists = data.logGroups.some(group => group.logGroupName === logGroupName);
if (!logGroupExists) {
throw new Error(`Log group '${logGroupName}' does not exist.`);
}
isStreaming = true;
updateStatus(`Connected to log group: ${logGroupName}`);
streamLogs(logGroupName);
} catch (error) {
updateStatus(`Error: ${error.message}`, true);
}
}
function stopStreaming() {
isStreaming = false;
updateStatus('Log streaming stopped.');
}
async function streamLogs(logGroupName) {
if (!isStreaming) return;
const startTime = Date.now() - (LOOKBACK_MINUTES * 60 * 1000);
try {
const data = await cloudWatchLogs.describeLogStreams({
logGroupName: logGroupName,
orderBy: 'LastEventTime',
descending: true,
limit: MAX_STREAMS
}).promise();
if (data.logStreams.length === 0) {
updateStatus(`No log streams found in log group ${logGroupName}`);
return;
}
const streamPromises = data.logStreams.map(async stream => {
const streamStartTime = lastIngestedMap[stream.logStreamName] || startTime;
try {
const eventsData = await cloudWatchLogs.getLogEvents({
logGroupName: logGroupName,
logStreamName: stream.logStreamName,
startTime: streamStartTime + 1,
startFromHead: true
}).promise();
if (eventsData.events && eventsData.events.length > 0) {
eventsData.events.forEach(event => {
displayLog(event);
});
lastIngestedMap[stream.logStreamName] = eventsData.events[eventsData.events.length - 1].timestamp;
}
} catch (error) {
console.error(`Error fetching logs from stream ${stream.logStreamName}:`, error);
}
});
await Promise.all(streamPromises);
if (isStreaming) {
setTimeout(() => streamLogs(logGroupName), POLL_INTERVAL);
}
} catch (error) {
console.error('Error:', error);
updateStatus(`Error: ${error.message}`, true);
if (isStreaming) {
setTimeout(() => streamLogs(logGroupName), POLL_INTERVAL);
}
}
}
function parseLogMessage(message) {
try {
if (message.trim().startsWith('{') && message.trim().endsWith('}')) {
const parsed = JSON.parse(message);
return {
timestamp: parsed.timestamp || parsed.time || parsed['@timestamp'],
level: parsed.level || parsed.severity || parsed.log_level || 'INFO',
message: parsed.message || parsed.msg || message,
raw: parsed
};
}
} catch (e) {
// Not valid JSON, continue with regex parsing
}
const levelMatch = message.match(/\b(ERROR|WARN(?:ING)?|INFO|DEBUG|TRACE)\b/i);
return {
timestamp: null,
level: levelMatch ? levelMatch[1].toUpperCase() : 'INFO',
message: message,
raw: null
};
}
function displayLog(event) {
const logContainer = document.getElementById('logContainer');
const logEntry = document.createElement('div');
logEntry.className = 'log-entry';
const timestamp = new Date(event.timestamp).toISOString();
const parsed = parseLogMessage(event.message);
let content = parsed.message;
if (parsed.raw) {
content = `<div class="json-content">${formatJSON(parsed.raw)}</div>`;
}
logEntry.innerHTML = `
<span class="timestamp">[${timestamp}]</span>
<span class="log-level ${parsed.level.toLowerCase()}">${parsed.level}</span>
<span class="log-content">${content}</span>
`;
logContainer.appendChild(logEntry);
logCount++;
updateLogCount();
if (autoScroll) {
logContainer.scrollTop = logContainer.scrollHeight;
}
// Add click handler for log entry
logEntry.addEventListener('click', () => {
document.querySelectorAll('.log-entry').forEach(entry => {
entry.classList.remove('selected');
});
logEntry.classList.add('selected');
});
}
</script>
</body>
</html>