changeset 8558:f6ee6d26b9bd

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.
author Mads Kiilerich <mads@kiilerich.com>
date Sun, 10 May 2020 21:31:56 +0200
parents 42312c8d070d
children fcff67b0de83
files kallithea/lib/colored_formatter.py
diffstat 1 files changed, 9 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/kallithea/lib/colored_formatter.py	Wed May 06 21:40:05 2020 +0200
+++ b/kallithea/lib/colored_formatter.py	Sun May 10 21:31:56 2020 +0200
@@ -13,6 +13,7 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 import logging
+import sys
 
 
 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(30, 38)
@@ -65,15 +66,18 @@
     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 @@
     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])