|
| 1 | +"""Logging Configurator for aca-py agent.""" |
| 2 | + |
| 3 | +import io |
| 4 | +import logging |
| 5 | +from importlib import resources |
| 6 | +from logging.config import ( |
| 7 | + dictConfigClass, |
| 8 | +) |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +import yaml |
| 12 | + |
| 13 | +LOGGER = logging.getLogger(__name__) |
| 14 | + |
| 15 | +def load_resource(path: str, encoding: Optional[str] = None): |
| 16 | + """Open a resource file located in a python package or the local filesystem. |
| 17 | +
|
| 18 | + Args: |
| 19 | + path (str): The resource path in the form of `dir/file` or `package:dir/file` |
| 20 | + encoding (str, optional): The encoding to use when reading the resource file. |
| 21 | + Defaults to None. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + file-like object: A file-like object representing the resource |
| 25 | + """ |
| 26 | + components = path.rsplit(":", 1) |
| 27 | + try: |
| 28 | + if len(components) == 1: |
| 29 | + # Local filesystem resource |
| 30 | + return open(components[0], encoding=encoding) |
| 31 | + else: |
| 32 | + # Package resource |
| 33 | + package, resource = components |
| 34 | + bstream = resources.files(package).joinpath(resource).open("rb") |
| 35 | + if encoding: |
| 36 | + return io.TextIOWrapper(bstream, encoding=encoding) |
| 37 | + return bstream |
| 38 | + except IOError: |
| 39 | + LOGGER.warning("Resource not found: %s", path) |
| 40 | + return None |
| 41 | + |
| 42 | + |
| 43 | +def dictConfig(config, new_file_path=None): |
| 44 | + """Custom dictConfig, https://github.com/python/cpython/blob/main/Lib/logging/config.py.""" |
| 45 | + if new_file_path: |
| 46 | + config["handlers"]["rotating_file"]["filename"] = f"{new_file_path}" |
| 47 | + dictConfigClass(config).configure() |
| 48 | + |
| 49 | + |
| 50 | +class LoggingConfigurator: |
| 51 | + """Utility class used to configure logging and print an informative start banner.""" |
| 52 | + |
| 53 | + @classmethod |
| 54 | + def configure( |
| 55 | + cls, |
| 56 | + log_config_path: Optional[str] = None, |
| 57 | + log_level: Optional[str] = None, |
| 58 | + log_file: Optional[str] = None, |
| 59 | + ): |
| 60 | + """Configure logger. |
| 61 | +
|
| 62 | + :param logging_config_path: str: (Default value = None) Optional path to |
| 63 | + custom logging config |
| 64 | +
|
| 65 | + :param log_level: str: (Default value = None) |
| 66 | +
|
| 67 | + :param log_file: str: (Default value = None) Optional file name to write logs to |
| 68 | + """ |
| 69 | + |
| 70 | + write_to_log_file = log_file is not None or log_file == "" |
| 71 | + |
| 72 | + # This is a check that requires a log file path to be provided if |
| 73 | + # --log-file is specified on startup and a config file is not. |
| 74 | + if not log_config_path and write_to_log_file and not log_file: |
| 75 | + raise ValueError( |
| 76 | + "log_file (--log-file) must be provided in single-tenant mode " |
| 77 | + "using the default config since a log file path is not set." |
| 78 | + ) |
| 79 | + |
| 80 | + cls._configure_logging( |
| 81 | + log_config_path=log_config_path, |
| 82 | + log_level=log_level, |
| 83 | + log_file=log_file, |
| 84 | + ) |
| 85 | + |
| 86 | + @classmethod |
| 87 | + def _configure_logging(cls, log_config_path, log_level, log_file): |
| 88 | + # Setup log config and log file if provided |
| 89 | + cls._setup_log_config_file(log_config_path, log_file) |
| 90 | + |
| 91 | + # Set custom file handler |
| 92 | + if log_file: |
| 93 | + logging.root.handlers.append(logging.FileHandler(log_file, encoding="utf-8")) |
| 94 | + |
| 95 | + # Set custom log level |
| 96 | + if log_level: |
| 97 | + logging.root.setLevel(log_level.upper()) |
| 98 | + |
| 99 | + @classmethod |
| 100 | + def _setup_log_config_file(cls, log_config_path, log_file): |
| 101 | + log_config, is_dict_config = cls._load_log_config(log_config_path) |
| 102 | + |
| 103 | + # Setup config |
| 104 | + if not log_config: |
| 105 | + logging.basicConfig(level=logging.WARNING) |
| 106 | + logging.root.warning(f"Logging config file not found: {log_config_path}") |
| 107 | + elif is_dict_config: |
| 108 | + dictConfig(log_config, new_file_path=log_file or None) |
| 109 | + |
| 110 | + @classmethod |
| 111 | + def _load_log_config(cls, log_config_path): |
| 112 | + if ".yml" in log_config_path or ".yaml" in log_config_path: |
| 113 | + with open(log_config_path, "r") as stream: |
| 114 | + return yaml.safe_load(stream), True |
| 115 | + return load_resource(log_config_path, "utf-8"), False |
0 commit comments