|
| 1 | +"""Centralized logging configuration using structlog.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +import sys |
| 5 | + |
| 6 | +import structlog |
| 7 | + |
| 8 | + |
| 9 | +def configure_logging(verbose: bool = False) -> None: |
| 10 | + """Configure structlog for the application. |
| 11 | +
|
| 12 | + Args: |
| 13 | + verbose: If True, set log level to DEBUG, otherwise INFO |
| 14 | + """ |
| 15 | + log_level = logging.DEBUG if verbose else logging.INFO |
| 16 | + |
| 17 | + # Configure standard library logging |
| 18 | + logging.basicConfig( |
| 19 | + format="%(message)s", |
| 20 | + stream=sys.stdout, |
| 21 | + level=log_level, |
| 22 | + ) |
| 23 | + |
| 24 | + # Configure structlog |
| 25 | + structlog.configure( |
| 26 | + processors=[ |
| 27 | + structlog.contextvars.merge_contextvars, |
| 28 | + structlog.processors.add_log_level, |
| 29 | + structlog.processors.StackInfoRenderer(), |
| 30 | + structlog.dev.set_exc_info, |
| 31 | + structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S", utc=False), |
| 32 | + structlog.dev.ConsoleRenderer(), |
| 33 | + ], |
| 34 | + wrapper_class=structlog.make_filtering_bound_logger(log_level), |
| 35 | + context_class=dict, |
| 36 | + logger_factory=structlog.PrintLoggerFactory(), |
| 37 | + cache_logger_on_first_use=True, |
| 38 | + ) |
| 39 | + |
| 40 | + |
| 41 | +def get_logger(name: str) -> structlog.BoundLogger: |
| 42 | + """Get a structlog logger for a module. |
| 43 | +
|
| 44 | + Args: |
| 45 | + name: Module name, typically __name__ |
| 46 | +
|
| 47 | + Returns: |
| 48 | + Configured structlog logger |
| 49 | + """ |
| 50 | + return structlog.get_logger(name) |
0 commit comments