Changeset - f6ee6d26b9bd
[Not reviewed]
default
0 1 0
Mads Kiilerich (mads) - 6 years ago 2020-05-10 21:31:56
mads@kiilerich.com
Grafted from: a0ffe0c2e60e
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.
1 file changed with 9 insertions and 2 deletions:
0 comments (0 inline, 0 general)
kallithea/lib/colored_formatter.py
Show inline comments
 
@@ -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 @@ 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])
0 comments (0 inline, 0 general)