From b9dc8826630c981fceba045ed72a52fe46a30132 Mon Sep 17 00:00:00 2001 From: deeplow Date: Mon, 16 Jan 2023 12:29:16 +0000 Subject: [PATCH] CLI: prefix non-INFO logs with log type In non-development mode, the CLI shows the user information via the INFO log level. The message is shown directly without [INFO] as a prefix. Otherwise it would quickly get annoying to the user seeing [INFO] on every line of a CLI application. However, if an error happens it's important for the user to recognize it's an error or a warning. This commit prints the log level in these cases. --- dangerzone/cli.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/dangerzone/cli.py b/dangerzone/cli.py index bd5e3a6..c36d1a5 100644 --- a/dangerzone/cli.py +++ b/dangerzone/cli.py @@ -105,11 +105,28 @@ args.override_parser_and_check_suspicious_options(cli_main) def setup_logging() -> None: + class EndUserLoggingFormatter(logging.Formatter): + """Prefixes any non-INFO log line with the log level""" + + def format(self, record: logging.LogRecord) -> str: + if record.levelno == logging.INFO: + # Bypass formatter: print line directly + return record.getMessage() + else: + return super().format(record) + if getattr(sys, "dangerzone_dev", False): fmt = "[%(levelname)-5s] %(message)s" logging.basicConfig(level=logging.DEBUG, format=fmt) else: - logging.basicConfig(level=logging.INFO, format="%(message)s") + # prefix non-INFO log lines with the respective log type + fmt = "%(levelname)s %(message)s" + formatter = EndUserLoggingFormatter(fmt=fmt) + ch = logging.StreamHandler() + ch.setFormatter(formatter) + logger = logging.getLogger() + logger.setLevel(logging.INFO) + logger.addHandler(ch) def display_banner() -> None: