logger.py 1.8 KB
Newer Older
1
import datetime
2
import logging
K
Kentaro Wada 已提交
3
import os
4 5 6

import termcolor

K
Kentaro Wada 已提交
7 8 9 10 11
if os.name == "nt":  # Windows
    import colorama

    colorama.init()

12 13 14 15
from . import __appname__


COLORS = {
K
Kentaro Wada 已提交
16 17 18 19 20
    "WARNING": "yellow",
    "INFO": "white",
    "DEBUG": "blue",
    "CRITICAL": "red",
    "ERROR": "red",
21 22 23 24
}


class ColoredFormatter(logging.Formatter):
25 26
    def __init__(self, fmt, use_color=True):
        logging.Formatter.__init__(self, fmt)
27 28 29 30 31
        self.use_color = use_color

    def format(self, record):
        levelname = record.levelname
        if self.use_color and levelname in COLORS:
32 33 34

            def colored(text):
                return termcolor.colored(
K
Kentaro Wada 已提交
35
                    text, color=COLORS[levelname], attrs={"bold": True},
36 37
                )

K
Kentaro Wada 已提交
38
            record.levelname2 = colored("{:<7}".format(record.levelname))
39 40 41
            record.message2 = colored(record.msg)

            asctime2 = datetime.datetime.fromtimestamp(record.created)
K
Kentaro Wada 已提交
42
            record.asctime2 = termcolor.colored(asctime2, color="green")
43

K
Kentaro Wada 已提交
44 45 46
            record.module2 = termcolor.colored(record.module, color="cyan")
            record.funcName2 = termcolor.colored(record.funcName, color="cyan")
            record.lineno2 = termcolor.colored(record.lineno, color="cyan")
47 48 49 50 51
        return logging.Formatter.format(self, record)


class ColoredLogger(logging.Logger):

52
    FORMAT = (
K
Kentaro Wada 已提交
53
        "[%(levelname2)s] %(module2)s:%(funcName2)s:%(lineno2)s - %(message2)s"
54
    )
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

    def __init__(self, name):
        logging.Logger.__init__(self, name, logging.INFO)

        color_formatter = ColoredFormatter(self.FORMAT)

        console = logging.StreamHandler()
        console.setFormatter(color_formatter)

        self.addHandler(console)
        return


logging.setLoggerClass(ColoredLogger)
logger = logging.getLogger(__appname__)