-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp-logger.js
More file actions
477 lines (405 loc) · 17.6 KB
/
mcp-logger.js
File metadata and controls
477 lines (405 loc) · 17.6 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/**
* Browser Logger - Frontend logging with HTTP transmission
* MVP Implementation - Simple, lightweight, focused on core functionality
*/
(function() {
'use strict';
class BrowserLogger {
constructor() {
this.config = {
backendUrl: window.MCP_LOGGING_BACKEND_URL || this.detectBackendUrl(),
enabled: window.MCP_LOGGING_ENABLED !== false, // Default to enabled
bufferSize: window.MCP_LOGGING_BUFFER_SIZE || 100,
batchInterval: window.MCP_LOGGING_BATCH_INTERVAL || 100,
appName: window.MCP_LOGGING_APP_NAME || 'unknown-app'
};
this.logBuffer = [];
this.batchTimer = null;
this.host = window.location.host;
this.app = this.config.appName;
this.isActive = false;
this.originalConsole = {};
this.fallbackBuffer = [];
this.retryTimer = null;
this.isBackendAvailable = true;
this.retryCount = 0;
this.maxRetries = 3;
this.retryDelay = 5000; // 5 seconds
this.isAutoLoaded = this.checkIfAutoLoaded();
}
async initialize() {
if (!this.isEnabled()) {
this.log_internal('debug', 'BrowserLogger: Logging disabled');
return;
}
if (this.isActive) {
this.log_internal('debug', 'BrowserLogger: Already active');
return;
}
try {
// Store original console methods BEFORE intercepting
this.originalConsole = {
log: console.log,
error: console.error,
warn: console.warn,
info: console.info,
debug: console.debug
};
this.interceptConsole();
this.captureErrors();
this.isActive = true;
this.log_internal('debug', `BrowserLogger: Active for app ${this.app} on host ${this.host}`);
this.log_internal('debug', `BrowserLogger: Backend URL: ${this.config.backendUrl}`);
// Register with backend if script was auto-loaded
if (this.isAutoLoaded) {
await this.registerWithBackend();
}
} catch (error) {
this.log_internal('error', 'BrowserLogger: Failed to initialize:', error);
}
}
log_internal(level, ...args) {
// Use original console methods for internal logger messages to avoid infinite loops
if (this.originalConsole && this.originalConsole[level]) {
this.originalConsole[level].apply(console, args);
} else {
console[level].apply(console, args);
}
}
interceptConsole() {
if (!this.isEnabled()) return;
const methods = ['log', 'error', 'warn', 'info', 'debug'];
methods.forEach(method => {
console[method] = (...args) => {
// Call original console method first
this.originalConsole[method].apply(console, args);
// Then capture the log
this.addConsoleLog(method, args);
};
});
}
addConsoleLog(level, args) {
const logEntry = {
timestamp: Date.now(),
level: level.toUpperCase(),
message: args.map(arg => {
if (typeof arg === 'object') {
try {
return JSON.stringify(arg, this.safeStringifyReplacer());
} catch {
return this.safeObjectToString(arg);
}
}
return String(arg);
}).join(' ')
};
this.addToBuffer('browser', [logEntry]);
}
log(namespace, data) {
if (!this.isEnabled()) return;
if (!namespace || typeof namespace !== 'string') {
this.log_internal('error', 'BrowserLogger: namespace must be a non-empty string');
return;
}
const logEntry = {
timestamp: Date.now(),
namespace,
data
};
this.addToBuffer(namespace, logEntry);
}
addToBuffer(namespace, data) {
if (!this.logBuffer) {
this.logBuffer = [];
}
this.logBuffer.push({
namespace,
data,
timestamp: Date.now()
});
if (this.logBuffer.length >= this.config.bufferSize) {
this.flushLogs();
} else {
this.scheduleFlush();
}
}
async flushLogs() {
if (!this.isEnabled() || this.logBuffer.length === 0) return;
const logsToSend = [...this.logBuffer];
this.logBuffer = [];
try {
const payload = {
app: this.app,
host: this.host,
logs: {}
};
// Group logs by namespace first, then format correctly
const groupedLogs = {};
logsToSend.forEach(log => {
if (!groupedLogs[log.namespace]) {
groupedLogs[log.namespace] = [];
}
groupedLogs[log.namespace].push(log.data);
});
// Now format according to backend expectations
Object.keys(groupedLogs).forEach(namespace => {
if (namespace === 'browser') {
// Browser logs: flatten into a single array
payload.logs[namespace] = [];
groupedLogs[namespace].forEach(logData => {
if (Array.isArray(logData)) {
payload.logs[namespace].push(...logData);
} else {
payload.logs[namespace].push(logData);
}
});
} else {
// Non-browser logs: send each as a separate array item
// Backend expects array for this case in handleLogSubmission
payload.logs[namespace] = groupedLogs[namespace];
}
});
// Validate and debug the payload before sending
let requestBody;
try {
requestBody = JSON.stringify(payload);
if (!requestBody || requestBody === '{}') {
throw new Error('Empty payload generated');
}
// Debug log the request (don't log full payload for privacy)
this.log_internal('debug', `BrowserLogger: Sending ${Object.keys(payload.logs || {}).length} namespaces to backend`);
} catch (stringifyError) {
this.log_internal('error', 'BrowserLogger: Failed to stringify payload:', stringifyError.message);
this.log_internal('debug', 'BrowserLogger: Payload preview:', {
app: payload.app,
host: payload.host,
logCount: Object.keys(payload.logs || {}).length,
namespaces: Object.keys(payload.logs || {})
});
throw stringifyError;
}
const response = await fetch(`${this.config.backendUrl}/api/logs/submit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: requestBody
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// Backend is available again if we were in fallback mode
if (!this.isBackendAvailable) {
this.isBackendAvailable = true;
this.retryCount = 0;
this.log_internal('debug', 'BrowserLogger: Backend connection restored');
// Try to flush any fallback logs
if (this.fallbackBuffer.length > 0) {
const fallbackLogs = [...this.fallbackBuffer];
this.fallbackBuffer = [];
this.logBuffer.unshift(...fallbackLogs);
this.scheduleFlush();
}
}
this.log_internal('debug', 'BrowserLogger: Logs sent successfully');
} catch (error) {
// Mark backend as unavailable
this.isBackendAvailable = false;
// Store in fallback buffer
this.fallbackBuffer.unshift(...logsToSend);
// Keep fallback buffer limited
if (this.fallbackBuffer.length > 500) {
this.fallbackBuffer = this.fallbackBuffer.slice(-500);
}
this.log_internal('error', 'BrowserLogger: Failed to send logs:', error.message);
this.log_internal('debug', 'BrowserLogger: Storing logs in fallback buffer');
// Schedule retry if not already in progress
if (!this.retryTimer && this.retryCount < this.maxRetries) {
this.scheduleRetry();
}
}
}
scheduleFlush() {
if (this.batchTimer) return;
this.batchTimer = setTimeout(() => {
this.flushLogs();
this.batchTimer = null;
}, this.config.batchInterval);
}
scheduleRetry() {
if (this.retryTimer) return;
this.retryCount++;
const delay = this.retryDelay * this.retryCount; // Exponential backoff
this.log_internal('debug', `BrowserLogger: Scheduling retry ${this.retryCount}/${this.maxRetries} in ${delay}ms`);
this.retryTimer = setTimeout(() => {
this.retryTimer = null;
if (this.fallbackBuffer.length > 0) {
// Move fallback logs to main buffer
const fallbackLogs = [...this.fallbackBuffer];
this.fallbackBuffer = [];
this.logBuffer.unshift(...fallbackLogs);
}
this.flushLogs();
}, delay);
}
captureErrors() {
window.addEventListener('error', (event) => {
this.addConsoleLog('error', [
`WINDOW ERROR: ${event.message} at ${event.filename}:${event.lineno}:${event.colno}`
]);
});
window.addEventListener('unhandledrejection', (event) => {
this.addConsoleLog('error', [
`UNHANDLED PROMISE REJECTION: ${event.reason}`
]);
});
const originalFetch = window.fetch;
const logger = this;
window.fetch = async function(...args) {
try {
const response = await originalFetch.apply(this, args);
if (!response.ok) {
const url = typeof args[0] === 'string' ? args[0] : args[0].url;
// Don't log fetch errors for logger's own requests to avoid infinite loop
if (!url.includes('/api/logs/submit')) {
logger.log_internal('error', `FETCH ${response.status} (${response.statusText}) ${url}`);
}
}
return response;
} catch (error) {
const url = typeof args[0] === 'string' ? args[0] : args[0].url;
// Don't log fetch errors for logger's own requests to avoid infinite loop
if (!url.includes('/api/logs/submit')) {
logger.log_internal('error', `FETCH ERROR ${url}: ${error.message}`);
}
throw error;
}
};
}
safeStringifyReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
}
return value;
};
}
safeObjectToString(obj) {
if (obj === null) return 'null';
if (obj === undefined) return 'undefined';
try {
const type = Object.prototype.toString.call(obj);
if (type === '[object Object]') {
const keys = Object.keys(obj).slice(0, 5); // Limit to first 5 keys
const keyValuePairs = keys.map(key => {
try {
const value = obj[key];
if (typeof value === 'function') return `${key}: [Function]`;
if (typeof value === 'object' && value !== null) {
return `${key}: ${Object.prototype.toString.call(value)}`;
}
return `${key}: ${String(value)}`;
} catch {
return `${key}: [Error accessing property]`;
}
});
const moreText = Object.keys(obj).length > 5 ? '...' : '';
return `{${keyValuePairs.join(', ')}${moreText}}`;
} else if (type === '[object Array]') {
return `[Array(${obj.length})]`;
} else {
return type;
}
} catch {
return '[Object]';
}
}
isEnabled() {
return this.config.enabled === true;
}
detectBackendUrl() {
// Auto-detect backend URL based on current page
const defaultUrls = [
'http://localhost:22345',
`http://${window.location.hostname}:22345`,
'http://127.0.0.1:22345'
];
// If running on same host as backend, use current hostname
if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
return defaultUrls[0];
}
return defaultUrls[1]; // Use current hostname with default port
}
checkIfAutoLoaded() {
// Check if script was loaded from backend server
const scripts = document.querySelectorAll('script[src]');
for (const script of scripts) {
if (script.src.includes('/mcp-logger.js')) {
const scriptUrl = new URL(script.src);
const expectedBackend = this.config.backendUrl.replace(/^https?:\/\//, '').replace(/:\d+$/, '');
const scriptHost = scriptUrl.hostname + (scriptUrl.port ? ':' + scriptUrl.port : '');
return scriptHost === expectedBackend.replace(/^https?:\/\//, '').replace(/:\d+$/, '');
}
}
return false;
}
isAutoLoaded() {
return this.isAutoLoaded;
}
async registerWithBackend() {
try {
const response = await fetch(`${this.config.backendUrl}/api/logs/submit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
app: this.app,
host: this.host,
logs: {
'client-registration': {
scriptUrl: document.currentScript ? document.currentScript.src : 'unknown',
userAgent: navigator.userAgent,
timestamp: Date.now(),
autoLoaded: true,
referrer: document.referrer,
appName: this.app
}
}
})
});
if (response.ok) {
this.log_internal('debug', 'BrowserLogger: Successfully registered with backend');
} else {
this.log_internal('warn', 'BrowserLogger: Failed to register with backend:', response.status);
}
} catch (error) {
this.log_internal('warn', 'BrowserLogger: Registration failed:', error.message);
}
}
destroy() {
if (this.batchTimer) {
clearTimeout(this.batchTimer);
}
if (this.retryTimer) {
clearTimeout(this.retryTimer);
}
Object.keys(this.originalConsole).forEach(method => {
console[method] = this.originalConsole[method];
});
this.isActive = false;
}
}
const logger = new BrowserLogger();
if (logger.isEnabled()) {
logger.initialize();
}
window.BrowserLogger = logger;
window.logger = {
log: (namespace, data) => logger.log(namespace, data)
};
})();