From d86a214d1c6fdbf80ba27304b77e0bbf95442641 Mon Sep 17 00:00:00 2001 From: William Woodruff Date: Tue, 27 Dec 2022 19:55:28 -0500 Subject: [PATCH] _cli: refactor logging (#452) * _cli: refactor logging This is inspired by the refactor in https://github.com/sigstore/sigstore-python/pull/372. Signed-off-by: William Woodruff * README: update `pip-audit --help` Signed-off-by: William Woodruff Signed-off-by: William Woodruff --- README.md | 5 ++--- pip_audit/_cli.py | 21 ++++++++++++++------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 62862aa4..cc80f4c0 100644 --- a/README.md +++ b/README.md @@ -179,9 +179,8 @@ optional arguments: --path PATH restrict to the specified installation path for auditing packages; this option can be used multiple times (default: []) - -v, --verbose give more output; this setting overrides the - `PIP_AUDIT_LOGLEVEL` variable and is equivalent to - setting it to `debug` (default: False) + -v, --verbose run with additional debug logging; supply multiple + times to increase verbosity (default: 0) --fix automatically upgrade dependencies with known vulnerabilities (default: False) --require-hashes require a hash to check each requirement against, for diff --git a/pip_audit/_cli.py b/pip_audit/_cli.py index e87a1395..c7085a8c 100644 --- a/pip_audit/_cli.py +++ b/pip_audit/_cli.py @@ -38,8 +38,13 @@ from pip_audit._state import AuditSpinner, AuditState from pip_audit._util import assert_never +logging.basicConfig() logger = logging.getLogger(__name__) -logging.basicConfig(level=os.environ.get("PIP_AUDIT_LOGLEVEL", "INFO").upper()) + +# NOTE: We configure the top package logger, rather than the root logger, +# to avoid overly verbose logging in third-party code by default. +package_logger = logging.getLogger("pip_audit") +package_logger.setLevel(os.environ.get("PIP_AUDIT_LOGLEVEL", "INFO").upper()) @contextmanager @@ -262,10 +267,9 @@ def _parser() -> argparse.ArgumentParser: # pragma: no cover parser.add_argument( "-v", "--verbose", - dest="verbose", - action="store_true", - help="give more output; this setting overrides the `PIP_AUDIT_LOGLEVEL` variable and is " - "equivalent to setting it to `debug`", + action="count", + default=0, + help="run with additional debug logging; supply multiple times to increase verbosity", ) parser.add_argument( "--fix", @@ -332,8 +336,11 @@ def _parser() -> argparse.ArgumentParser: # pragma: no cover def _parse_args(parser: argparse.ArgumentParser) -> argparse.Namespace: # pragma: no cover args = parser.parse_args() - if args.verbose: - logging.root.setLevel("DEBUG") + # Configure logging upfront, so that we don't miss anything. + if args.verbose >= 1: + package_logger.setLevel("DEBUG") + if args.verbose >= 2: + logging.getLogger().setLevel("DEBUG") logger.debug(f"parsed arguments: {args}")