-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_app.py
More file actions
249 lines (218 loc) Β· 8.49 KB
/
debug_app.py
File metadata and controls
249 lines (218 loc) Β· 8.49 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
#!/usr/bin/env python3
"""
Simplified Flask app to test error handling improvements
"""
import os
import sys
import json
import logging
import traceback
from datetime import datetime
from flask import Flask, request, jsonify
from flask_cors import CORS
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev-secret-key')
CORS(app, origins=["http://localhost:3000", "http://localhost:5000"])
# Configure detailed logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('debug.log', mode='a')
]
)
logger = logging.getLogger(__name__)
@app.before_request
def log_request_info():
"""Log detailed request information"""
logger.info(f"π Request: {request.method} {request.url}")
logger.info(f"π Headers: {dict(request.headers)}")
if request.is_json:
logger.info(f"π JSON Data: {request.get_json(silent=True)}")
if request.form:
logger.info(f"π Form Data: {dict(request.form)}")
if request.args:
logger.info(f"π Query Args: {dict(request.args)}")
@app.after_request
def log_response_info(response):
"""Log response information"""
logger.info(f"π€ Response Status: {response.status_code}")
return response
@app.errorhandler(Exception)
def handle_all_exceptions(error):
"""Handle all unhandled exceptions with maximum detail"""
error_id = datetime.utcnow().strftime('%Y%m%d_%H%M%S_%f')
# Log everything we can about the error
logger.error(f"π¨ CRITICAL ERROR [{error_id}]")
logger.error(f"π₯ Exception Type: {type(error).__name__}")
logger.error(f"π₯ Exception Message: {str(error)}")
logger.error(f"π Request URL: {request.url}")
logger.error(f"π‘ Request Method: {request.method}")
logger.error(f"π·οΈ Request Endpoint: {request.endpoint}")
logger.error(f"π Request Headers: {dict(request.headers)}")
if request.is_json:
logger.error(f"π Request JSON: {request.get_json(silent=True)}")
if request.form:
logger.error(f"π Request Form: {dict(request.form)}")
if request.args:
logger.error(f"π Request Args: {dict(request.args)}")
logger.error(f"π Full Traceback:\\n{traceback.format_exc()}")
# Return comprehensive error response
error_response = {
'error': 'Internal server error',
'error_id': error_id,
'error_type': type(error).__name__,
'error_message': str(error),
'timestamp': datetime.utcnow().isoformat(),
'request_info': {
'url': request.url,
'method': request.method,
'endpoint': request.endpoint,
'headers': dict(request.headers),
'json_data': request.get_json(silent=True) if request.is_json else None,
'form_data': dict(request.form) if request.form else None,
'query_args': dict(request.args) if request.args else None
},
'debug_info': {
'traceback': traceback.format_exc().split('\\n'),
'python_version': f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
'flask_version': 'unknown'
}
}
return jsonify(error_response), 500
@app.route('/')
def index():
"""Home route with debug info"""
return jsonify({
'message': 'Documentation.AI Debug Server',
'status': 'running',
'timestamp': datetime.utcnow().isoformat(),
'endpoints': {
'home': '/',
'health': '/api/health',
'debug': '/api/debug',
'test_error': '/api/test-error'
}
})
@app.route('/favicon.ico')
def favicon():
"""Handle favicon requests"""
logger.info("π Favicon requested")
return '', 204
@app.route('/api/health')
def health_check():
"""Comprehensive health check"""
try:
logger.info("π₯ Health check requested")
# Environment check
env_vars = {
'GITHUB_TOKEN': 'β
Set' if os.getenv('GITHUB_TOKEN') else 'β Missing',
'GEMINI_API_KEY': 'β
Set' if os.getenv('GEMINI_API_KEY') else 'β Missing',
'SECRET_KEY': 'β
Set' if os.getenv('SECRET_KEY') else 'β Using default'
}
return jsonify({
'status': 'healthy',
'timestamp': datetime.utcnow().isoformat(),
'version': 'debug-1.0.0',
'environment': env_vars,
'system_info': {
'python_version': f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
'cwd': os.getcwd(),
'debug_mode': app.debug
}
})
except Exception as e:
logger.error(f"β Health check failed: {e}")
logger.error(traceback.format_exc())
return jsonify({
'status': 'unhealthy',
'error': str(e),
'traceback': traceback.format_exc().split('\\n')
}), 500
@app.route('/api/debug')
def debug_info():
"""Debug endpoint with detailed system information"""
try:
logger.info("π§ Debug info requested")
import sys
import platform
return jsonify({
'debug_info': {
'timestamp': datetime.utcnow().isoformat(),
'python': {
'version': sys.version,
'executable': sys.executable,
'path': sys.path[:5] # First 5 paths only
},
'platform': {
'system': platform.system(),
'release': platform.release(),
'machine': platform.machine()
},
'flask': {
'debug_mode': app.debug,
'testing': app.testing,
'secret_key_set': bool(app.secret_key)
},
'environment': dict(os.environ) # This might be sensitive, be careful
}
})
except Exception as e:
logger.error(f"β Debug info failed: {e}")
raise # Let the global error handler catch this
@app.route('/api/test-error')
def test_error():
"""Endpoint to test error handling"""
logger.info("π₯ Test error requested")
error_type = request.args.get('type', 'generic')
if error_type == 'value':
raise ValueError("This is a test ValueError")
elif error_type == 'key':
raise KeyError("This is a test KeyError")
elif error_type == 'type':
raise TypeError("This is a test TypeError")
elif error_type == 'import':
# This will raise ImportError
exec("import non_existent_module")
else:
raise Exception("This is a generic test exception")
return jsonify({'message': 'This should not be reached'})
@app.route('/api/analyze', methods=['POST'])
def analyze_repository():
"""Test analyze endpoint to replicate the 500 error"""
try:
logger.info("π Analyze endpoint called")
# Validate request
if not request.is_json:
logger.error("β Request is not JSON")
return jsonify({'error': 'Request must be JSON'}), 400
data = request.get_json()
logger.info(f"π Request data: {data}")
repo_url = data.get('repo_url', '').strip()
if not repo_url:
logger.error("β Repository URL is missing")
return jsonify({'error': 'Repository URL is required'}), 400
# Simulate the error that's happening
logger.info("π¨ Simulating the actual error...")
raise Exception("AI models not available - import failed during initialization")
except Exception as e:
logger.error(f"π₯ Analyze failed: {e}")
logger.error(traceback.format_exc())
raise # Let the global error handler catch this
if __name__ == '__main__':
logger.info("π Starting Documentation.AI Debug Server")
logger.info(f"π Debug mode: {app.debug}")
logger.info(f"π Current working directory: {os.getcwd()}")
# Test imports at startup
logger.info("π§ͺ Testing imports at startup...")
try:
import flask
logger.info(f"β
Flask imported successfully")
except Exception as e:
logger.error(f"β Flask import failed: {e}")
app.run(host='0.0.0.0', port=5001, debug=True)