Fred808 commited on
Commit
36fedea
·
verified ·
1 Parent(s): fcbaea0

Upload error_logger.py

Browse files
Files changed (1) hide show
  1. error_logger.py +122 -0
error_logger.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import traceback
3
+ from datetime import datetime
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Dict, Any, Optional
7
+
8
+ # Configure logging
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
12
+ handlers=[
13
+ logging.FileHandler('api_errors.log'),
14
+ logging.StreamHandler()
15
+ ]
16
+ )
17
+
18
+ logger = logging.getLogger("api.errors")
19
+
20
+ class ErrorLogger:
21
+ def __init__(self):
22
+ self.error_log_file = "detailed_errors.json"
23
+ self.errors: Dict[str, Any] = self._load_errors()
24
+
25
+ def _load_errors(self) -> Dict[str, Any]:
26
+ """Load existing errors from file"""
27
+ try:
28
+ if Path(self.error_log_file).exists():
29
+ with open(self.error_log_file, 'r') as f:
30
+ return json.load(f)
31
+ except Exception as e:
32
+ logger.error(f"Failed to load error log: {e}")
33
+ return {}
34
+
35
+ def _save_errors(self):
36
+ """Save errors to file"""
37
+ try:
38
+ with open(self.error_log_file, 'w') as f:
39
+ json.dump(self.errors, f, indent=2)
40
+ except Exception as e:
41
+ logger.error(f"Failed to save error log: {e}")
42
+
43
+ def log_error(self,
44
+ error: Exception,
45
+ endpoint: str,
46
+ request_info: Optional[Dict] = None,
47
+ context: Optional[Dict] = None):
48
+ """
49
+ Log detailed error information
50
+
51
+ Args:
52
+ error: The exception that occurred
53
+ endpoint: The API endpoint where the error occurred
54
+ request_info: Dictionary containing request information
55
+ context: Additional context about the error
56
+ """
57
+ timestamp = datetime.now().isoformat()
58
+ error_id = f"{timestamp}-{hash(str(error))}"
59
+
60
+ error_data = {
61
+ "timestamp": timestamp,
62
+ "error_type": error.__class__.__name__,
63
+ "error_message": str(error),
64
+ "endpoint": endpoint,
65
+ "traceback": traceback.format_exc(),
66
+ "request_info": request_info or {},
67
+ "context": context or {}
68
+ }
69
+
70
+ # Store in memory
71
+ self.errors[error_id] = error_data
72
+
73
+ # Save to file
74
+ self._save_errors()
75
+
76
+ # Log to standard logging
77
+ logger.error(
78
+ f"Error in {endpoint}: {error.__class__.__name__} - {str(error)}\n"
79
+ f"Context: {json.dumps(context or {}, indent=2)}\n"
80
+ f"Request: {json.dumps(request_info or {}, indent=2)}\n"
81
+ f"Traceback: {traceback.format_exc()}"
82
+ )
83
+
84
+ return error_id
85
+
86
+ def get_error(self, error_id: str) -> Optional[Dict]:
87
+ """Retrieve detailed error information by ID"""
88
+ return self.errors.get(error_id)
89
+
90
+ def get_recent_errors(self, limit: int = 10) -> Dict[str, Any]:
91
+ """Get most recent errors"""
92
+ sorted_errors = sorted(
93
+ self.errors.items(),
94
+ key=lambda x: x[1]["timestamp"],
95
+ reverse=True
96
+ )
97
+ return dict(sorted_errors[:limit])
98
+
99
+ def get_error_summary(self) -> Dict[str, Any]:
100
+ """Get summary of errors by type"""
101
+ summary = {}
102
+ for error_id, error_data in self.errors.items():
103
+ error_type = error_data["error_type"]
104
+ if error_type not in summary:
105
+ summary[error_type] = {
106
+ "count": 0,
107
+ "last_occurrence": None,
108
+ "endpoints": set()
109
+ }
110
+
111
+ summary[error_type]["count"] += 1
112
+ summary[error_type]["endpoints"].add(error_data["endpoint"])
113
+
114
+ if (not summary[error_type]["last_occurrence"] or
115
+ error_data["timestamp"] > summary[error_type]["last_occurrence"]):
116
+ summary[error_type]["last_occurrence"] = error_data["timestamp"]
117
+
118
+ # Convert sets to lists for JSON serialization
119
+ for error_type in summary:
120
+ summary[error_type]["endpoints"] = list(summary[error_type]["endpoints"])
121
+
122
+ return summary