-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathlogging.py
More file actions
257 lines (203 loc) · 7.14 KB
/
Copy pathlogging.py
File metadata and controls
257 lines (203 loc) · 7.14 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
"""Logging Utilities.
This module provides logging configuration and utilities for the AI backend.
"""
import json
import logging
import logging.config
import sys
from datetime import datetime
from typing import Any, ClassVar
import structlog
class JSONFormatter(logging.Formatter):
"""Custom JSON formatter for structured logging."""
def format(self, record: logging.LogRecord) -> str:
"""Format log record as JSON.
Args:
record: Log record to format
Returns:
JSON formatted log string
"""
log_data = {
"timestamp": datetime.fromtimestamp(record.created).isoformat(),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
"module": record.module,
"function": record.funcName,
"line": record.lineno,
}
# Add exception info if present
if record.exc_info:
log_data["exception"] = self.formatException(record.exc_info)
# Add extra fields
for key, value in record.__dict__.items():
if key not in [
"name",
"msg",
"args",
"levelname",
"levelno",
"pathname",
"filename",
"module",
"lineno",
"funcName",
"created",
"msecs",
"relativeCreated",
"thread",
"threadName",
"processName",
"process",
"getMessage",
"exc_info",
"exc_text",
"stack_info",
]:
log_data[key] = value
return json.dumps(log_data, default=str)
class ColoredFormatter(logging.Formatter):
"""Colored formatter for console output in development."""
# Color codes
COLORS: ClassVar[dict[str, str]] = {
"DEBUG": "\033[36m", # Cyan
"INFO": "\033[32m", # Green
"WARNING": "\033[33m", # Yellow
"ERROR": "\033[31m", # Red
"CRITICAL": "\033[35m", # Magenta
"RESET": "\033[0m", # Reset
}
def format(self, record: logging.LogRecord) -> str:
"""Format log record with colors.
Args:
record: Log record to format
Returns:
Colored log string
"""
color = self.COLORS.get(record.levelname, self.COLORS["RESET"])
reset = self.COLORS["RESET"]
# Format timestamp
timestamp = datetime.fromtimestamp(record.created).strftime("%Y-%m-%d %H:%M:%S")
# Create formatted message
log_format = f"{color}[{timestamp}] {record.levelname:8s}{reset} | {record.name:20s} | {record.getMessage()}"
# Add exception info if present
if record.exc_info:
log_format += f"\n{self.formatException(record.exc_info)}"
return log_format
def setup_logging(
level: str | None = None,
format_type: str | None = None,
enable_structlog: bool = True,
) -> None:
"""Set up logging configuration.
Args:
level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
format_type: Format type ('json' or 'colored')
enable_structlog: Whether to enable structlog
"""
# Use settings if not provided
from config.settings import get_settings
try:
app_settings = get_settings()
level = level or app_settings.LOG_LEVEL
format_type = format_type or app_settings.LOG_FORMAT
except RuntimeError:
# Fallback to defaults if settings not available
level = level or "INFO"
format_type = format_type or "colored"
# Configure root logger
root_logger = logging.getLogger()
root_logger.setLevel(getattr(logging, level))
# Remove existing handlers
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
# Create console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(getattr(logging, level))
# Set formatter based on format type
formatter: logging.Formatter = (
JSONFormatter() if format_type.lower() == "json" else ColoredFormatter()
)
console_handler.setFormatter(formatter)
root_logger.addHandler(console_handler)
# Configure specific loggers
configure_specific_loggers()
# Set up structlog if enabled
if enable_structlog:
setup_structlog()
logging.info(f"Logging configured - Level: {level}, Format: {format_type}")
def configure_specific_loggers() -> None:
"""Configure specific loggers with appropriate levels."""
# Set external library log levels
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("aiohttp").setLevel(logging.WARNING)
logging.getLogger("openai").setLevel(logging.INFO)
logging.getLogger("supabase").setLevel(logging.INFO)
def setup_structlog() -> None:
"""Set up structlog for structured logging."""
structlog.configure(
processors=[
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.add_log_level,
structlog.processors.StackInfoRenderer(),
structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
logger_factory=structlog.PrintLoggerFactory(),
context_class=dict,
cache_logger_on_first_use=True,
)
def get_logger(name: str) -> Any:
"""Get a structured logger instance.
Args:
name: Logger name
Returns:
Structured logger instance
"""
return structlog.get_logger(name)
class LoggerMixin:
"""Mixin class to add logging capabilities to other classes."""
@property
def logger(self) -> Any:
"""Get logger for this class."""
return get_logger(self.__class__.__name__)
def log_function_call(func: Any) -> Any:
"""Decorator to log function calls with parameters and results.
Args:
func: Function to decorate
Returns:
Decorated function
"""
from functools import wraps
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
logger = get_logger(func.__module__)
# Log function entry
logger.debug(
"Function called",
function=func.__name__,
args=args[:3] if len(args) > 3 else args, # Limit args to prevent spam
kwargs=kwargs,
)
try:
result = func(*args, **kwargs)
logger.debug(
"Function completed",
function=func.__name__,
result_type=type(result).__name__,
)
return result
except Exception as e:
logger.error(
"Function failed",
function=func.__name__,
error=str(e),
error_type=type(e).__name__,
)
raise
return wrapper
# Initialize logging when module is imported
if not logging.getLogger().handlers:
setup_logging()