diff --git a/inboard/logging_conf.py b/inboard/logging_conf.py index a0732bb..b2ff4b9 100644 --- a/inboard/logging_conf.py +++ b/inboard/logging_conf.py @@ -4,30 +4,42 @@ import os import sys from pathlib import Path +from typing import Optional + + +def find_and_load_logging_conf(logging_conf: str) -> dict: + """Find and load a logging configuration module or file.""" + logging_conf_path = Path(logging_conf) + spec = ( + importlib.util.spec_from_file_location("confspec", logging_conf_path) + if logging_conf_path.is_file() and logging_conf_path.suffix == ".py" + else importlib.util.find_spec(logging_conf) + ) + if not spec: + raise ImportError(f"Unable to import {logging_conf_path}") + logging_conf_module = importlib.util.module_from_spec(spec) + exec_module = getattr(spec.loader, "exec_module") + exec_module(logging_conf_module) + if not hasattr(logging_conf_module, "LOGGING_CONFIG"): + raise AttributeError(f"No LOGGING_CONFIG in {logging_conf_module.__name__}") + logging_conf_dict = getattr(logging_conf_module, "LOGGING_CONFIG") + if not isinstance(logging_conf_dict, dict): + raise TypeError("LOGGING_CONFIG is not a dictionary instance") + return logging_conf_dict def configure_logging( logger: logging.Logger = logging.getLogger(), - logging_conf: str = os.getenv("LOGGING_CONF", "inboard.logging_conf"), + logging_conf: Optional[str] = os.getenv("LOGGING_CONF"), ) -> dict: - """Configure Python logging based on a path to a logging module or file.""" + """Configure Python logging given the name of a logging module or file.""" try: - logging_conf_path = Path(logging_conf) - spec = ( - importlib.util.spec_from_file_location("confspec", logging_conf_path) - if logging_conf_path.is_file() and logging_conf_path.suffix == ".py" - else importlib.util.find_spec(logging_conf) - ) - if not spec: - raise ImportError(f"Unable to import {logging_conf}") - logging_conf_module = importlib.util.module_from_spec(spec) - exec_module = getattr(spec.loader, "exec_module") - exec_module(logging_conf_module) - if not hasattr(logging_conf_module, "LOGGING_CONFIG"): - raise AttributeError(f"No LOGGING_CONFIG in {logging_conf_module.__name__}") - logging_conf_dict = getattr(logging_conf_module, "LOGGING_CONFIG") - if not isinstance(logging_conf_dict, dict): - raise TypeError("LOGGING_CONFIG is not a dictionary instance") + if not logging_conf: + logging_conf_path = __name__ + logging_conf_dict = LOGGING_CONFIG + else: + logging_conf_path = logging_conf + logging_conf_dict = find_and_load_logging_conf(logging_conf_path) logging.config.dictConfig(logging_conf_dict) logger.debug(f"Logging dict config loaded from {logging_conf_path}.") return logging_conf_dict