File size: 11,492 Bytes
00dd8ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42651db
 
 
 
 
 
 
 
 
 
 
 
00dd8ea
 
 
 
 
 
 
42651db
00dd8ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
"""
BeatDebate Logging Configuration

Comprehensive logging system for the BeatDebate application that provides:
- Structured logging with JSON output
- File rotation and organization
- Component-specific log levels
- Performance monitoring
- Error tracking
- API request/response logging
"""

import logging
import logging.handlers
import os
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional

import structlog
from structlog.contextvars import bind_contextvars, clear_contextvars


class BeatDebateLogger:
    """
    Centralized logging configuration for BeatDebate.
    
    Provides structured logging with:
    - File rotation by size and time
    - Component-specific log levels
    - JSON formatting for structured data
    - Console output for development
    - Separate files for different log types
    """
    
    def __init__(
        self,
        log_dir: str = "logs",
        log_level: str = "INFO",
        enable_console: bool = True,
        max_file_size: int = 10 * 1024 * 1024,  # 10MB
        backup_count: int = 5
    ):
        """
        Initialize the logging system.
        
        Args:
            log_dir: Directory to store log files
            log_level: Default log level
            enable_console: Whether to enable console logging
            max_file_size: Maximum size per log file before rotation
            backup_count: Number of backup files to keep
        """
        self.log_dir = Path(log_dir)
        self.log_level = getattr(logging, log_level.upper())
        self.enable_console = enable_console
        self.max_file_size = max_file_size
        self.backup_count = backup_count
        
        # Create log directory
        self.log_dir.mkdir(exist_ok=True)
        
        # Component-specific log levels
        self.component_levels = {
            "main": logging.INFO,        # Main application flow
            "ui": logging.WARNING,       # Keep UI less verbose
            "external": logging.WARNING, # External API calls (less noise)
        }
        
        self._setup_logging()
    
    def _setup_logging(self):
        """Configure the complete logging system."""
        # Clear any existing configuration
        logging.getLogger().handlers.clear()
        
        # Configure structlog
        self._configure_structlog()
        
        # Setup file handlers
        self._setup_file_handlers()
        
        # Setup console handler
        if self.enable_console:
            self._setup_console_handler()
        
        # Configure component-specific loggers
        self._configure_component_loggers()
        
        # Set up root logger
        root_logger = logging.getLogger()
        root_logger.setLevel(self.log_level)
    
    def _configure_structlog(self):
        """Configure structlog for structured logging."""
        # Shared processors for all outputs
        shared_processors = [
            structlog.stdlib.add_log_level,
            structlog.stdlib.add_logger_name,
            structlog.processors.TimeStamper(fmt="ISO"),
            structlog.processors.StackInfoRenderer(),
            structlog.processors.format_exc_info,
            structlog.processors.UnicodeDecoder(),
        ]
        
        # Configure structlog
        structlog.configure(
            processors=shared_processors + [
                structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
            ],
            context_class=dict,
            logger_factory=structlog.stdlib.LoggerFactory(),
            wrapper_class=structlog.stdlib.BoundLogger,
            cache_logger_on_first_use=True,
        )
    
    def _setup_file_handlers(self):
        """Setup rotating file handlers for essential log categories."""
        
        # Main application log - captures everything
        main_handler = self._create_rotating_file_handler(
            filename="beatdebate.log",
            level=self.log_level
        )
        
        # Errors only - for quick debugging
        error_handler = self._create_rotating_file_handler(
            filename="errors.log",
            level=logging.ERROR
        )
        
        # Add handlers to root logger
        root_logger = logging.getLogger()
        for handler in [main_handler, error_handler]:
            root_logger.addHandler(handler)
    
    def _create_rotating_file_handler(
        self, 
        filename: str, 
        level: int
    ) -> logging.handlers.RotatingFileHandler:
        """Create a rotating file handler with JSON formatting."""
        
        filepath = self.log_dir / filename
        
        handler = logging.handlers.RotatingFileHandler(
            filename=filepath,
            maxBytes=self.max_file_size,
            backupCount=self.backup_count,
            encoding='utf-8'
        )
        
        handler.setLevel(level)
        
        # JSON formatter for structured data
        formatter = structlog.stdlib.ProcessorFormatter(
            processor=structlog.dev.ConsoleRenderer(colors=False),
        )
        
        handler.setFormatter(formatter)
        return handler
    
    def _setup_console_handler(self):
        """Setup console handler for development."""
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(self.log_level)
        
        # Colored console output for development
        formatter = structlog.stdlib.ProcessorFormatter(
            processor=structlog.dev.ConsoleRenderer(colors=True),
        )
        
        console_handler.setFormatter(formatter)
        
        # Add to root logger
        logging.getLogger().addHandler(console_handler)
    
    def _configure_component_loggers(self):
        """Configure specific loggers for different components."""
        
        # If global log level is DEBUG, don't override component levels
        # This allows all modules to show debug logs when LOG_LEVEL=DEBUG
        if self.log_level == logging.DEBUG:
            # When debugging, we want to see logs from all components
            # Only reduce noise from truly external libraries
            external_modules = ["httpx", "requests", "urllib3", "urllib3.connectionpool"]
            for ext_module in external_modules:
                logger = logging.getLogger(ext_module)
                logger.setLevel(logging.WARNING)  # Still reduce noise from HTTP libraries
            return
        
        # Normal operation: apply component-specific log levels
        # UI loggers (less verbose)
        ui_modules = ["src.ui.chat_interface", "src.ui.response_formatter"]
        for ui_module in ui_modules:
            logger = logging.getLogger(ui_module)
            logger.setLevel(self.component_levels["ui"])
        
        # External API loggers (reduce noise)
        external_modules = ["httpx", "requests", "urllib3", "urllib3.connectionpool"]
        for ext_module in external_modules:
            logger = logging.getLogger(ext_module)
            logger.setLevel(self.component_levels["external"])
    
    def get_logger(self, name: str) -> structlog.BoundLogger:
        """Get a structured logger for a specific component."""
        return structlog.get_logger(name)
    
    def set_request_context(self, request_id: str, user_id: Optional[str] = None):
        """Set context for the current request."""
        clear_contextvars()
        bind_contextvars(
            request_id=request_id,
            user_id=user_id,
            timestamp=datetime.utcnow().isoformat()
        )
    
    def log_performance(
        self, 
        operation: str, 
        duration: float, 
        **kwargs
    ):
        """Log performance metrics."""
        perf_logger = self.get_logger("performance")
        perf_logger.info(
            "performance_metric",
            operation=operation,
            duration_seconds=duration,
            **kwargs
        )
    
    def log_api_request(
        self,
        method: str,
        url: str,
        status_code: int,
        duration: float,
        **kwargs
    ):
        """Log API request details."""
        api_logger = self.get_logger("api")
        api_logger.info(
            "api_request",
            method=method,
            url=url,
            status_code=status_code,
            duration_seconds=duration,
            **kwargs
        )
    
    def log_agent_reasoning(
        self,
        agent: str,
        step: str,
        confidence: float,
        **kwargs
    ):
        """Log agent reasoning steps."""
        agent_logger = self.get_logger("agents")
        agent_logger.info(
            "agent_reasoning",
            agent=agent,
            step=step,
            confidence=confidence,
            **kwargs
        )
    
    def log_error(
        self,
        error: Exception,
        context: Dict[str, Any],
        **kwargs
    ):
        """Log errors with full context."""
        error_logger = self.get_logger("errors")
        error_logger.error(
            "error_occurred",
            error_type=type(error).__name__,
            error_message=str(error),
            context=context,
            **kwargs
        )


# Global logger instance
_logger_instance: Optional[BeatDebateLogger] = None


def setup_logging(
    log_dir: str = "logs",
    log_level: str = "INFO",
    enable_console: bool = True,
    **kwargs
) -> BeatDebateLogger:
    """
    Setup the global logging configuration.
    
    Args:
        log_dir: Directory to store log files
        log_level: Default log level
        enable_console: Whether to enable console logging
        **kwargs: Additional arguments for BeatDebateLogger
    
    Returns:
        Configured logger instance
    """
    global _logger_instance
    
    _logger_instance = BeatDebateLogger(
        log_dir=log_dir,
        log_level=log_level,
        enable_console=enable_console,
        **kwargs
    )
    
    return _logger_instance


def get_logger(name: str) -> structlog.BoundLogger:
    """
    Get a logger for a specific component.
    
    Args:
        name: Component name
        
    Returns:
        Structured logger instance
        
    Raises:
        RuntimeError: If logging hasn't been setup
    """
    if _logger_instance is None:
        raise RuntimeError("Logging not setup. Call setup_logging() first.")
    
    return _logger_instance.get_logger(name)


def log_performance(operation: str, duration: float, **kwargs):
    """Log performance metrics."""
    if _logger_instance:
        _logger_instance.log_performance(operation, duration, **kwargs)


def log_api_request(method: str, url: str, status_code: int, duration: float, **kwargs):
    """Log API request details."""
    if _logger_instance:
        _logger_instance.log_api_request(method, url, status_code, duration, **kwargs)


def log_agent_reasoning(agent: str, step: str, confidence: float, **kwargs):
    """Log agent reasoning steps."""
    if _logger_instance:
        _logger_instance.log_agent_reasoning(agent, step, confidence, **kwargs)


def log_error(error: Exception, context: Dict[str, Any], **kwargs):
    """Log errors with full context."""
    if _logger_instance:
        _logger_instance.log_error(error, context, **kwargs)


def set_request_context(request_id: str, user_id: Optional[str] = None):
    """Set context for the current request."""
    if _logger_instance:
        _logger_instance.set_request_context(request_id, user_id)