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.
This commit is contained in:
deeplow 2023-01-16 12:29:16 +00:00
parent c442c443df
commit b9dc882663
No known key found for this signature in database
GPG key ID: 577982871529A52A

View file

@ -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: