logs.py 1.96 KB
Newer Older
1 2
import inspect
import logging
Guillaume Binet's avatar
Guillaume Binet committed
3 4
import sys

5 6 7 8
COLORS = {'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', }

NO_COLORS = {'DEBUG': '', 'INFO': '', 'WARNING': '', 'ERROR': '', 'CRITICAL': '', }

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

def ispydevd():
    for frame in inspect.stack():
        if frame[1].endswith("pydevd.py"):
            return True
    return False


root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)

pydev = ispydevd()
stream = sys.stdout if pydev else sys.stderr
isatty = pydev or stream.isatty()  # force isatty if we are under pydev because it supports coloring anyway.
console_hdlr = logging.StreamHandler(stream)

25 26 27 28 29 30 31 32

def get_log_colors(theme_color=None):
    """Return a tuple containing the log format string and a log color dict"""
    if theme_color == 'light':
        text_color_theme = 'white'
    elif theme_color == 'dark':
        text_color_theme = 'black'
    else:  # Anything else produces nocolor
33
        return '%(name)-25.25s%(reset)s %(message)s%(reset)s', NO_COLORS
34

35
    return f'%(name)-25.25s%(reset)s %({text_color_theme})s%(message)s%(reset)s', COLORS
36 37


38 39 40 41 42 43 44 45
def format_logs(formatter=None, theme_color=None):
    """
    You may either use the formatter parameter to provide your own
    custom formatter, or the theme_color parameter to use the
    built in color scheme formatter.
    """
    if formatter:
        console_hdlr.setFormatter(formatter)
46
    # if isatty and not True:
47
    elif isatty:
48 49
        from colorlog import ColoredFormatter  # noqa
        log_format, colors_dict = get_log_colors(theme_color)
50
        color_formatter = ColoredFormatter(
51
            "%(asctime)s %(log_color)s%(levelname)-8s%(reset)s " + log_format,
52 53 54 55
            datefmt="%H:%M:%S",
            reset=True,
            log_colors=colors_dict,
        )
56
        console_hdlr.setFormatter(color_formatter)
57 58 59
    else:
        console_hdlr.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)-25s %(message)s"))
    root_logger.addHandler(console_hdlr)