Coverage for rust2rpm/log.py: 96%
22 statements
« prev ^ index » next coverage.py v7.6.7, created at 2024-11-26 13:52 +0100
« prev ^ index » next coverage.py v7.6.7, created at 2024-11-26 13:52 +0100
1"""Module containing a simple logging implementation.
3Logged messages are by default wrapped to width of the current terminal window,
4multi-line messages are pretty-printed.
6Output is colorized according to "severity":
8- info (no color)
9- errors (red)
10- warnings (yellow)
11- success (green)
12"""
14import shutil
15import sys
16import textwrap
18from termcolor import colored
20NOWRAP = False
21"""Global variable that controls whether log messages are wrapped to the width
22of the current terminal window or not. Setting this to `True` can be useful for
23debugging or testing purposes, since it makes the messages printed to stderr
24deterministic and independent of the current environment."""
27def _eprint(message: str):
28 # T201: this print is used to implement custom logging
29 print(message, file=sys.stderr) # noqa: T201
32def _wrap(message: str, prefix: str, width: int | None = None) -> list[str]:
33 if NOWRAP:
34 return [f"{prefix} {message}"]
36 if not width: 36 ↛ 39line 36 didn't jump to line 39 because the condition on line 36 was always true
37 width = shutil.get_terminal_size().columns
39 return textwrap.wrap(message, 80, initial_indent=f"{prefix} ", subsequent_indent=" " * (len(prefix) + 1))
42def success(message: str):
43 """Log a message for an action that finished successfully."""
44 _eprint(colored("\n".join(_wrap(message, "•")), "green"))
47def info(message: str):
48 """Log a purely informational message."""
49 _eprint("\n".join(_wrap(message, "•")))
52def warn(message: str):
53 """Log a warning message.
55 This is associated with potential problems that are however non-fatal.
56 """
57 _eprint(colored("\n".join(_wrap(message, "WARNING:")), "yellow"))
60def error(message: str):
61 """Log an error message.
63 This is usually associated with hard errors that cause the program to exit.
64 """
65 _eprint(colored("\n".join(_wrap(message, "ERROR:")), "red", attrs=["dark"]))