diamond-in commited on
Commit
ace9c2b
·
verified ·
1 Parent(s): 492241f

Update features/monitoring.py

Browse files
Files changed (1) hide show
  1. features/monitoring.py +135 -0
features/monitoring.py CHANGED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Network monitoring and performance analysis features
3
+ """
4
+ import json
5
+ import time
6
+ import logging
7
+ from browser.driver import get_driver, cleanup_driver
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ def monitor_network_requests(url: str, duration: int = 5, use_persistent: bool = False) -> str:
12
+ """Monitor network requests made by a page"""
13
+ driver = None
14
+ try:
15
+ driver = get_driver(None, use_persistent) # Don't navigate yet
16
+
17
+ # Inject JavaScript to monitor network
18
+ monitor_script = """
19
+ window.networkRequests = [];
20
+ const originalFetch = window.fetch;
21
+ const originalXHR = window.XMLHttpRequest.prototype.open;
22
+
23
+ // Monitor fetch requests
24
+ window.fetch = function(...args) {
25
+ const request = {
26
+ method: args[1]?.method || 'GET',
27
+ url: args[0],
28
+ timestamp: new Date().toISOString(),
29
+ type: 'fetch'
30
+ };
31
+ window.networkRequests.push(request);
32
+ return originalFetch.apply(this, args);
33
+ };
34
+
35
+ // Monitor XHR requests
36
+ window.XMLHttpRequest.prototype.open = function(method, url) {
37
+ const request = {
38
+ method: method,
39
+ url: url,
40
+ timestamp: new Date().toISOString(),
41
+ type: 'xhr'
42
+ };
43
+ window.networkRequests.push(request);
44
+ return originalXHR.apply(this, arguments);
45
+ };
46
+ """
47
+
48
+ # Navigate to page and inject monitoring
49
+ driver.get(url)
50
+ driver.execute_script(monitor_script)
51
+
52
+ # Wait and collect requests
53
+ time.sleep(duration)
54
+
55
+ # Get collected requests
56
+ requests = driver.execute_script("return window.networkRequests;")
57
+
58
+ # Also get performance entries
59
+ performance_entries = driver.execute_script("""
60
+ return performance.getEntriesByType('resource').map(entry => ({
61
+ name: entry.name,
62
+ type: entry.initiatorType,
63
+ duration: entry.duration,
64
+ size: entry.transferSize,
65
+ startTime: entry.startTime
66
+ }));
67
+ """)
68
+
69
+ result = {
70
+ "intercepted_requests": requests,
71
+ "performance_entries": performance_entries,
72
+ "total_requests": len(requests) + len(performance_entries)
73
+ }
74
+
75
+ return json.dumps(result, indent=2, default=str)
76
+ except Exception as e:
77
+ logger.error(f"Error in monitor_network_requests: {e}")
78
+ return f"Error: {e}"
79
+ finally:
80
+ cleanup_driver(driver, use_persistent)
81
+
82
+ def get_console_logs(url: str, use_persistent: bool = False) -> str:
83
+ """Capture browser console logs"""
84
+ driver = None
85
+ try:
86
+ driver = get_driver(None, use_persistent)
87
+
88
+ # Inject console log capture before navigation
89
+ driver.execute_script("""
90
+ window.consoleLogs = [];
91
+ const originalLog = console.log;
92
+ const originalError = console.error;
93
+ const originalWarn = console.warn;
94
+
95
+ console.log = function(...args) {
96
+ window.consoleLogs.push({
97
+ type: 'log',
98
+ message: args.join(' '),
99
+ timestamp: new Date().toISOString()
100
+ });
101
+ originalLog.apply(console, args);
102
+ };
103
+
104
+ console.error = function(...args) {
105
+ window.consoleLogs.push({
106
+ type: 'error',
107
+ message: args.join(' '),
108
+ timestamp: new Date().toISOString()
109
+ });
110
+ originalError.apply(console, args);
111
+ };
112
+
113
+ console.warn = function(...args) {
114
+ window.consoleLogs.push({
115
+ type: 'warn',
116
+ message: args.join(' '),
117
+ timestamp: new Date().toISOString()
118
+ });
119
+ originalWarn.apply(console, args);
120
+ };
121
+ """)
122
+
123
+ # Navigate to page
124
+ driver.get(url)
125
+ time.sleep(3) # Wait for logs
126
+
127
+ # Get captured logs
128
+ logs = driver.execute_script("return window.consoleLogs;")
129
+
130
+ return json.dumps(logs, indent=2, default=str)
131
+ except Exception as e:
132
+ logger.error(f"Error in get_console_logs: {e}")
133
+ return f"Error: {e}"
134
+ finally:
135
+ cleanup_driver(driver, use_persistent)