Phase 3.1: Type Safety - Add bridge_types.py for shared type aliases (EventDict, PowerWatts, Timestamp, DeviceID) - Define protocols for callbacks and message parsers - Strict type annotations on all core modules (session_detector, event_queue, device_manager) - Fix Optional handling and type guards throughout codebase - Achieve full mypy compliance: 0 errors across 47 source files Phase 3.2: Logging Unification - Migrate from stdlib logging to pure structlog across all runtime modules - Convert all logs to structured event+fields format (snake_case event names) - Remove f-string and printf-style logger calls - Add contextvars support for per-request correlation - Implement FastAPI middleware to bind request_id, http_method, http_path - Propagate X-Request-ID header in responses - Remove stdlib logging imports except setup layer (utils/logging.py) - Ensure log-level consistency across all modules Files Modified: - iot_bridge/bridge_types.py (new) - Central type definitions - iot_bridge/core/* - Type safety and logging unification - iot_bridge/clients/* - Structured logging with request context - iot_bridge/parsers/* - Type-safe parsing with structured logs - iot_bridge/utils/logging.py - Pure structlog setup with contextvars - iot_bridge/api/server.py - Added request correlation middleware - iot_bridge/tests/* - Test fixtures updated for type safety - iot_bridge/OPTIMIZATION_PLAN.md - Phase 3 status updated Validation: - mypy . → 0 errors (47 files) - All unit tests pass - Runtime behavior unchanged - API response headers include X-Request-ID
46 lines
1.1 KiB
Python
46 lines
1.1 KiB
Python
"""Logging setup for IoT Bridge."""
|
|
|
|
import structlog
|
|
|
|
from config import LoggingConfig
|
|
|
|
|
|
LOG_LEVELS: dict[str, int] = {
|
|
"critical": 50,
|
|
"error": 40,
|
|
"warning": 30,
|
|
"info": 20,
|
|
"debug": 10,
|
|
"notset": 0,
|
|
}
|
|
|
|
|
|
def setup_logging(config: LoggingConfig):
|
|
"""Configure structured logging with structlog."""
|
|
|
|
# Set log level
|
|
log_level = LOG_LEVELS.get(config.level.lower(), LOG_LEVELS["info"])
|
|
|
|
renderer_processor = (
|
|
structlog.processors.JSONRenderer()
|
|
if config.format == "json"
|
|
else structlog.dev.ConsoleRenderer()
|
|
)
|
|
|
|
structlog.configure(
|
|
processors=[
|
|
structlog.contextvars.merge_contextvars,
|
|
structlog.processors.add_log_level,
|
|
structlog.processors.TimeStamper(fmt="iso"),
|
|
structlog.processors.StackInfoRenderer(),
|
|
structlog.processors.format_exc_info,
|
|
renderer_processor,
|
|
],
|
|
context_class=dict,
|
|
wrapper_class=structlog.make_filtering_bound_logger(log_level),
|
|
logger_factory=structlog.PrintLoggerFactory(),
|
|
cache_logger_on_first_use=True,
|
|
)
|
|
|
|
return structlog.get_logger()
|