|
| 1 | +"""Logging configuration for the MqPy application. |
| 2 | +
|
| 3 | +This module provides a centralized logging configuration for the entire application. |
| 4 | +Import this module instead of directly importing the logging module to ensure consistent |
| 5 | +logging behavior across the application. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import logging |
| 11 | +import sys |
| 12 | + |
| 13 | + |
| 14 | +def get_logger(name: str, level: int | None = None) -> logging.Logger: |
| 15 | + """Get a logger with the specified name and level. |
| 16 | +
|
| 17 | + Args: |
| 18 | + name (str): The name of the logger, typically __name__. |
| 19 | + level (int | None): The logging level. Defaults to INFO if None. |
| 20 | +
|
| 21 | + Returns: |
| 22 | + logging.Logger: A configured logger instance. |
| 23 | + """ |
| 24 | + logger = logging.getLogger(name) |
| 25 | + |
| 26 | + # Only configure the logger if it doesn't already have handlers |
| 27 | + if not logger.handlers: |
| 28 | + # Set default level if not specified |
| 29 | + if level is None: |
| 30 | + level = logging.INFO |
| 31 | + |
| 32 | + logger.setLevel(level) |
| 33 | + |
| 34 | + # Create console handler with a specific format |
| 35 | + console_handler = logging.StreamHandler(sys.stdout) |
| 36 | + formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") |
| 37 | + console_handler.setFormatter(formatter) |
| 38 | + logger.addHandler(console_handler) |
| 39 | + |
| 40 | + return logger |
| 41 | + |
| 42 | + |
| 43 | +# Configure the root logger |
| 44 | +root_logger = logging.getLogger() |
| 45 | +if not root_logger.handlers: |
| 46 | + root_logger.setLevel(logging.WARNING) |
| 47 | + console_handler = logging.StreamHandler(sys.stdout) |
| 48 | + formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") |
| 49 | + console_handler.setFormatter(formatter) |
| 50 | + root_logger.addHandler(console_handler) |
0 commit comments