# HG changeset patch # User Mads Kiilerich # Date 2020-05-10 21:31:56 # Node ID f6ee6d26b9bda6deea59bec506e0352cf3b66889 # Parent 42312c8d070df8ac5b55568cd433360c94d2c047 logging: try to avoid using ANSI color codes when not logging to a terminal Color on the console is nice, but it is annoying to get these codes when for example redirecting to a file. The formatter doesn't know exactly where the message will be used - it is fully configurable. In the default configuration, the messages are passed to a StreamHandler to sys.stderr . As an approximate optmization, hardcode the color formatters to only emit color formatting if logging to something that isatty. diff --git a/kallithea/lib/colored_formatter.py b/kallithea/lib/colored_formatter.py --- a/kallithea/lib/colored_formatter.py +++ b/kallithea/lib/colored_formatter.py @@ -13,6 +13,7 @@ # along with this program. If not, see . import logging +import sys BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(30, 38) @@ -65,15 +66,18 @@ class ColorFormatter(logging.Formatter): def __init__(self, *args, **kwargs): # can't do super(...) here because Formatter is an old school class logging.Formatter.__init__(self, *args, **kwargs) + self.plain = not getattr(sys.stderr, 'isatty', lambda: False)() def format(self, record): """ Changes record's levelname to use with COLORS enum """ + def_record = logging.Formatter.format(self, record) + if self.plain: + return def_record levelname = record.levelname start = COLOR_SEQ % (COLORS[levelname]) - def_record = logging.Formatter.format(self, record) end = RESET_SEQ colored_record = ''.join([start, def_record, end]) @@ -85,14 +89,17 @@ class ColorFormatterSql(logging.Formatte def __init__(self, *args, **kwargs): # can't do super(...) here because Formatter is an old school class logging.Formatter.__init__(self, *args, **kwargs) + self.plain = not getattr(sys.stderr, 'isatty', lambda: False)() def format(self, record): """ Changes record's levelname to use with COLORS enum """ + def_record = format_sql(logging.Formatter.format(self, record)) + if self.plain: + return def_record start = COLOR_SEQ % (COLORS['SQL']) - def_record = format_sql(logging.Formatter.format(self, record)) end = RESET_SEQ colored_record = ''.join([start, def_record, end])