代碼原理很簡單,在需要加顏色的地方加上控制顏色顯示的語義即可。
第三方模塊
# Create a logger object.
import logging
logger = logging.getLogger('your-module')
# Initialize coloredlogs.
import coloredlogs
coloredlogs.install(level='DEBUG')
# Some examples.
logger.debug("this is a debugging message")
logger.info("this is an informational message")
logger.warn("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a critical message")
效果圖
純代碼實現
import logging
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#The background is set with 40 plus the number of the color, and the foreground with 30
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"
def formatter_message(message, use_color = True):
if use_color:
message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
else:
message = message.replace("$RESET", "").replace("$BOLD", "")
return message
COLORS = {
'WARNING': YELLOW,
'INFO': WHITE,
'DEBUG': BLUE,
'CRITICAL': YELLOW,
'ERROR': RED
}
class ColoredFormatter(logging.Formatter):
def __init__(self, msg, use_color = True):
logging.Formatter.__init__(self, msg)
self.use_color = use_color
def format(self, record):
levelname = record.levelname
if self.use_color and levelname in COLORS:
levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
record.levelname = levelname_color
return logging.Formatter.format(self, record)
# Custom logger class with multiple destinations
class ColoredLogger(logging.Logger):
FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s] %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
COLOR_FORMAT = formatter_message(FORMAT, True)
def __init__(self, name):
logging.Logger.__init__(self, name, logging.DEBUG)
color_formatter = ColoredFormatter(self.COLOR_FORMAT)
console = logging.StreamHandler()
console.setFormatter(color_formatter)
self.addHandler(console)
return
#
logging.setLoggerClass(ColoredLogger)
color_log = logging.getLogger(__name__)
color_log.setLevel(logging.DEBUG)
color_log.debug("test")
color_log.info("test")
color_log.warning("test")
color_log.error("test")
color_log.critical("test")
效果圖
日誌等級怎麼用
日誌等級 | 何時使用 |
---|---|
DEBUG | 詳細信息,調試問題用。 |
INFO | 確認程序的工作符合預期。 |
WARNING | 指出一個無法預料的事件發生,或者一個即將發生的錯誤,如空間不足,軟件能繼續工作。 |
ERROR | 因爲一些嚴重的問題,導致軟件的有些功能無法正常工作 |
CRITICAL | 一個嚴重的錯誤,指明程序可能無法繼續運行 |
原帖:
How can I color Python logging output?
參考: