diff --git a/src/ansible_compat/runtime.py b/src/ansible_compat/runtime.py index 853d0119..f4f7c659 100644 --- a/src/ansible_compat/runtime.py +++ b/src/ansible_compat/runtime.py @@ -93,6 +93,7 @@ def __init__( require_module: bool = False, max_retries: int = 0, environ: Optional[dict[str, str]] = None, + verbosity: int = 0, ) -> None: """Initialize Ansible runtime environment. @@ -114,11 +115,16 @@ def __init__( Default is 0, no retries. :param environ: Environment dictionary to use, if undefined ``os.environ`` will be copied and used. + :param verbosity: Verbosity level to use. """ self.project_dir = project_dir or Path.cwd() self.isolated = isolated self.max_retries = max_retries self.environ = environ or os.environ.copy() + self.verbosity = verbosity + + self.initialize_logger(level=self.verbosity) + # Reduce noise from paramiko, unless user already defined PYTHONWARNINGS # paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated # https://github.com/paramiko/paramiko/issues/2038 @@ -159,6 +165,21 @@ def warning( # Monkey patch ansible warning in order to use warnings module. Display.warning = warning + def initialize_logger(self, level: int = 0) -> None: + """Set up the global logging level based on the verbosity number.""" + verbosity_map = { + -2: logging.CRITICAL, + -1: logging.ERROR, + 0: logging.WARNING, + 1: logging.INFO, + 2: logging.DEBUG, + } + # Unknown logging level is treated as DEBUG + logging_level = verbosity_map.get(level, logging.DEBUG) + _logger.setLevel(logging_level) + # Use module-level _logger instance to validate it + _logger.debug("Logging initialized to level %s", logging_level) + def load_collections(self) -> None: """Load collection data.""" self.collections = OrderedDict() @@ -426,9 +447,11 @@ def install_requirements( # noqa: C901 "ansible-galaxy", "role", "install", - "-vvvr", + "-r", f"{requirement}", ] + if self.verbosity > 0: + cmd.extend(["-" + ("v" * self.verbosity)]) if self.cache_dir: cmd.extend(["--roles-path", f"{self.cache_dir}/roles"]) @@ -440,7 +463,7 @@ def install_requirements( # noqa: C901 _logger.info("Running %s", " ".join(cmd)) result = self.run(cmd, retry=retry) - _logger.info(result.stdout) + _logger.debug(result.stdout) if result.returncode != 0: _logger.error(result.stderr) raise AnsibleCommandError(result) @@ -451,8 +474,9 @@ def install_requirements( # noqa: C901 "ansible-galaxy", "collection", "install", - "-vvv", ] + if self.verbosity > 0: + cmd.extend(["-" + ("v" * self.verbosity)]) if offline: _logger.warning( "Skipped installing collection dependencies due to running in offline mode.", @@ -473,7 +497,7 @@ def install_requirements( # noqa: C901 retry=retry, env={**os.environ, "ANSIBLE_COLLECTIONS_PATH": ":".join(cpaths)}, ) - _logger.info(result.stdout) + _logger.debug(result.stdout) if result.returncode != 0: _logger.error(result.stderr) raise AnsibleCommandError(result)