1+ import logging
2+ from datetime import datetime
3+ import json
4+ import traceback
5+
6+ class ColoredFormatter (logging .Formatter ):
7+ """Custom formatter with colors for console output"""
8+
9+ # Color codes
10+ COLORS = {
11+ 'DEBUG' : '\033 [36m' , # Cyan
12+ 'INFO' : '\033 [32m' , # Green
13+ 'WARNING' : '\033 [33m' , # Yellow
14+ 'ERROR' : '\033 [31m' , # Red
15+ 'CRITICAL' : '\033 [35m' , # Magenta
16+ 'RESET' : '\033 [0m' # Reset
17+ }
18+
19+ def format (self , record ):
20+ # Add color to levelname
21+ if hasattr (record , 'levelname' ):
22+ color = self .COLORS .get (record .levelname , self .COLORS ['RESET' ])
23+ record .levelname = f"{ color } { record .levelname } { self .COLORS ['RESET' ]} "
24+
25+ # Format the message
26+ formatted = super ().format (record )
27+
28+ # Add context information if present
29+ if hasattr (record , 'context' ) and record .context :
30+ context_str = json .dumps (record .context , indent = 2 )
31+ formatted += f"\n 📋 Context: { context_str } "
32+
33+ return formatted
34+
35+
36+ class JsonFormatter (logging .Formatter ):
37+ """JSON formatter for structured logging"""
38+
39+ def format (self , record ):
40+ log_entry = {
41+ 'timestamp' : datetime .fromtimestamp (record .created ).isoformat (),
42+ 'level' : record .levelname ,
43+ 'logger' : record .name ,
44+ 'message' : record .getMessage (),
45+ 'module' : record .module ,
46+ 'function' : record .funcName ,
47+ 'line' : record .lineno ,
48+ 'thread' : record .thread ,
49+ 'thread_name' : record .threadName
50+ }
51+
52+ # Add context information
53+ if hasattr (record , 'context' ):
54+ log_entry ['context' ] = record .context
55+
56+ if hasattr (record , 'user_id' ):
57+ log_entry ['user_id' ] = record .user_id
58+
59+ if hasattr (record , 'request_id' ):
60+ log_entry ['request_id' ] = record .request_id
61+
62+ if hasattr (record , 'ip_address' ):
63+ log_entry ['ip_address' ] = record .ip_address
64+
65+ if hasattr (record , 'endpoint' ):
66+ log_entry ['endpoint' ] = record .endpoint
67+
68+ if hasattr (record , 'method' ):
69+ log_entry ['method' ] = record .method
70+
71+ if hasattr (record , 'duration' ):
72+ log_entry ['duration' ] = record .duration
73+
74+ if hasattr (record , 'status_code' ):
75+ log_entry ['status_code' ] = record .status_code
76+
77+ # Add exception information
78+ if record .exc_info :
79+ log_entry ['exception' ] = {
80+ 'type' : record .exc_info [0 ].__name__ ,
81+ 'message' : str (record .exc_info [1 ]),
82+ 'traceback' : traceback .format_exception (* record .exc_info )
83+ }
84+
85+ return json .dumps (log_entry , ensure_ascii = False )
0 commit comments