From c25ab516642febdf3edf165282e1e946cfa81c32 Mon Sep 17 00:00:00 2001 From: Dima Gerasimov Date: Wed, 21 Jun 2023 19:56:33 +0100 Subject: [PATCH] core: some tweaks for better colour handling when we're redirecting stdout/stderr --- my/core/logging.py | 6 ++++-- my/core/preinit.py | 3 +++ my/core/warnings.py | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/my/core/logging.py b/my/core/logging.py index 47cd135..43f0767 100644 --- a/my/core/logging.py +++ b/my/core/logging.py @@ -128,10 +128,12 @@ def setup_logger(logger: str | logging.Logger, *, level: LevelIsh = None) -> Non else: # log_color/reset are specific to colorlog 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 # 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) diff --git a/my/core/preinit.py b/my/core/preinit.py index 9d6b374..88bcb27 100644 --- a/my/core/preinit.py +++ b/my/core/preinit.py @@ -1,5 +1,8 @@ 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: import appdirs import os diff --git a/my/core/warnings.py b/my/core/warnings.py index b5c1a9b..7051f34 100644 --- a/my/core/warnings.py +++ b/my/core/warnings.py @@ -16,7 +16,7 @@ def _colorize(x: str, color: Optional[str]=None) -> str: if color is None: return x - if not sys.stdout.isatty(): + if not sys.stderr.isatty(): return x # click handles importing/initializing colorama if necessary # on windows it installs it if necessary