背景:项目大了,日志混乱。需要进行规范。方便调试和查看。
功能:封装成工具类方便后续使用。直接保存为单独的py文件即可直接运行。
语音:python3.7+。推荐3.9
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
create:
author:
fuction:
"""
import logging
import colorlog
class Logger(object):
def __init__(self, logger):
log_colors_config = {
'DEBUG': 'white', # cyan white
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
self.logger = logging.getLogger(name=logger)
# 输出到控制台
console_handler = logging.StreamHandler()
# 输出到文件
file_handler = logging.FileHandler(filename='../logs/flask.log', mode='a', encoding='utf8')
# 日志级别,logger 和 handler以最高级别为准,不同handler之间可以不一样,不相互影响
self.logger.setLevel(logging.DEBUG)
console_handler.setLevel(logging.DEBUG)
file_handler.setLevel(logging.INFO)
# 日志输出格式
file_formatter = logging.Formatter(
fmt='[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console_formatter = colorlog.ColoredFormatter(
fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> line:%(lineno)d %(funcName)s [%(levelname)s] : %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
log_colors=log_colors_config
)
console_handler.setFormatter(console_formatter)
file_handler.setFormatter(file_formatter)
# 重复日志问题:
# 1、防止多次addHandler;
# 2、loggername 保证每次添加的时候不一样;
# 3、显示完log之后调用removeHandler
if not self.logger.handlers:
self.logger.addHandler(console_handler)
self.logger.addHandler(file_handler)
console_handler.close()
file_handler.close()
def debug(self, msg):
"""
定义输出的颜色debug--white,info--green,warning/error/critical--red
:param msg: 输出的log文字
:return:
"""
self.logger.debug(msg)
def info(self, msg):
self.logger.info(msg)
def warning(self, msg):
self.logger.warning(msg)
def error(self, msg):
self.logger.error(msg)
def critical(self, msg):
self.logger.critical(msg)
if __name__ == '__main__':
log = Logger("test")
log.debug('debug')
log.info('info')
log.warning('warning')
log.error('error')
log.critical('critical')