python日志通过不同的等级打印不同的颜色(示例代码)
程序员文章站
2022-05-13 12:18:40
1,不用第三方库# coding: utf-8import loggingblack, red, green, yellow, blue, magenta, cyan, white = range(8...
1,不用第三方库
# coding: utf-8 import logging black, red, green, yellow, blue, magenta, cyan, white = range(8) reset_seq = "\033[0m" color_seq = "\033[1;%dm" colors = { 'warning': green, '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 message = str(record.msg) funcname = record.funcname if self.use_color and levelname in colors: levelname_color = color_seq % (30 + colors[levelname]) + levelname + reset_seq message_color = color_seq % (30 + colors[levelname]) + message + reset_seq funcname_color = color_seq % (30 + colors[levelname]) + funcname + reset_seq record.levelname = levelname_color record.msg = message_color record.funcname = funcname_color return logging.formatter.format(self, record) logformat = "[%(asctime)s][%(name)s] [%(levelname)s] (%(filename)s:%(funcname)s:%(lineno)d) %(message)s" log_level = logging.debug formatter = coloredformatter(logformat) stream = logging.streamhandler() stream.setlevel(log_level) stream.setformatter(formatter) logging.root.setlevel(log_level) log = logging.getlogger('logconfig') log.setlevel(log_level) log.addhandler(stream) def logging(name): log = logging.getlogger(name) log.setlevel(log_level) log.addhandler(stream) return log if __name__ == '__main__': logger = logging(__name__) logger.info(123123) logger.debug(123123) logger.error(123123) logger.warning(123123)
2,使用colorlog pip install colorlog
# coding: utf-8 # coding: utf-8 from colorlog import coloredformatter import logging log_level = logging.debug logformat = "[%(asctime)s][%(name)s] [%(log_color)s**%(levelname)s**%(reset)s] [%(filename)s:%(funcname)s:%(log_color)s%(lineno)d%(reset)s] %(log_color)s%(message)s%(reset)s" logging.root.setlevel(log_level) formatter = coloredformatter(logformat) stream = logging.streamhandler() stream.setlevel(log_level) stream.setformatter(formatter) log = logging.getlogger('logconfig') log.setlevel(log_level) log.addhandler(stream) def logging(name): log = logging.getlogger(name) log.setlevel(log_level) log.addhandler(stream) return log if __name__ == '__main__': logging = logging("test") logging.info(123123) logging.warning(123123) logging.debug(123123)
3,华丽的日志
pip install logbook termcc dataclasses
#coding: utf-8 from logbook import logger from termcc.helper.logger import sample_flask as setup_logger setup_logger() logging = logger(__name__) logging.info("123123") logging.debug("123123") logging.warn("123123")
到此这篇关于python日志通过不同的等级打印不同的颜色的文章就介绍到这了,更多相关python根据日志级别打印颜色内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 唐朝名将李靖,是如何逐渐被民间神话的?