Python colorlog 控制台带颜色输出
0、介绍
Python想要实现控制台的输出带颜色,可以使用logging+colorlog模块
1、字体颜色
import logging import colorlog def init_log(): logger = logging.getLogger('ROOT') logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) fmt_string = '%(log_color)s[%(name)s][%(levelname)s]%(message)s' # black red green yellow blue purple cyan 和 white log_colors = { 'DEBUG': 'white', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'purple' } fmt = colorlog.ColoredFormatter(fmt_string, log_colors=log_colors) stream_handler.setFormatter(fmt) logger.addHandler(stream_handler) return logger if __name__ == '__main__': log = init_log() log.debug('debug message') log.info('info message') log.warning('warning message') log.error('error message') log.critical('critical message')
2、背景色
import logging import colorlog def init_log(): logger = logging.getLogger('ROOT') logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) fmt_string = '%(log_color)s[%(name)s][%(levelname)s]%(message)s' # black red green yellow blue purple cyan 和 white log_colors = { 'DEBUG': 'black,bg_white', 'INFO': 'bg_green', 'WARNING': 'bg_yellow', 'ERROR': 'bg_red', 'CRITICAL': 'bg_purple' } fmt = colorlog.ColoredFormatter(fmt_string, log_colors=log_colors) stream_handler.setFormatter(fmt) logger.addHandler(stream_handler) return logger if __name__ == '__main__': log = init_log() log.debug('debug message') log.info('info message') log.warning('warning message') log.error('error message') log.critical('critical message')
3、加粗
import logging import colorlog def init_log(): logger = logging.getLogger('ROOT') logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) fmt_string = '%(log_color)s[%(name)s][%(levelname)s]%(message)s' # black red green yellow blue purple cyan 和 white log_colors = { 'DEBUG': 'white,bold', 'INFO': 'green,bold', 'WARNING': 'yellow,bold', 'ERROR': 'red,bold', 'CRITICAL': 'purple,bold' } fmt = colorlog.ColoredFormatter(fmt_string, log_colors=log_colors) stream_handler.setFormatter(fmt) logger.addHandler(stream_handler) return logger if __name__ == '__main__': log = init_log() log.debug('debug message') log.info('info message') log.warning('warning message') log.error('error message') log.critical('critical message')
参考 https://bearfly1990.github.io/2018/04/25/colorlog/