core: some tweaks for better colour handling when we're redirecting stdout/stderr

This commit is contained in:
Dima Gerasimov 2023-06-21 19:56:33 +01:00 committed by karlicoss
parent 6f6be5c78e
commit c25ab51664
3 changed files with 8 additions and 3 deletions

View file

@ -128,10 +128,12 @@ def setup_logger(logger: str | logging.Logger, *, level: LevelIsh = None) -> Non
else: else:
# log_color/reset are specific to colorlog # log_color/reset are specific to colorlog
FORMAT_COLOR = FORMAT.format(start='%(log_color)s', end='%(reset)s') FORMAT_COLOR = FORMAT.format(start='%(log_color)s', end='%(reset)s')
fmt = FORMAT_COLOR if ch.stream.isatty() else FORMAT_NOCOLOR
# colorlog should detect tty in principle, but doesn't handle everything for some reason # colorlog should detect tty in principle, but doesn't handle everything for some reason
# see https://github.com/borntyping/python-colorlog/issues/71 # see https://github.com/borntyping/python-colorlog/issues/71
formatter = colorlog.ColoredFormatter(fmt) if ch.stream.isatty():
formatter = colorlog.ColoredFormatter(FORMAT_COLOR)
else:
formatter = logging.Formatter(FORMAT_NOCOLOR)
ch.setFormatter(formatter) ch.setFormatter(formatter)

View file

@ -1,5 +1,8 @@
from pathlib import Path from pathlib import Path
# todo preinit isn't really a good name? it's only in a separate file because
# - it's imported from my.core.init (so we wan't to keep this file as small/reliable as possible, hence not common or something)
# - we still need this function in __main__, so has to be separate from my/core/init.py
def get_mycfg_dir() -> Path: def get_mycfg_dir() -> Path:
import appdirs import appdirs
import os import os

View file

@ -16,7 +16,7 @@ def _colorize(x: str, color: Optional[str]=None) -> str:
if color is None: if color is None:
return x return x
if not sys.stdout.isatty(): if not sys.stderr.isatty():
return x return x
# click handles importing/initializing colorama if necessary # click handles importing/initializing colorama if necessary
# on windows it installs it if necessary # on windows it installs it if necessary