python中日志级别
可以通过level参数,设置不同的日志级别。当设置为高的日志级别时,低于此级别的日志不再打印。
五种日志级别按从低到高排序:
DEBUG < INFO < WARNING < ERROR < CRITICAL
- level设置为DEBUG级别,所有的日志都会打印
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s -%(message)s')
logging.debug('Some debugging details.')
logging.info('The logging module is working')
logging.warning('An error message is about to be logged.')
logging.error('An error has occurred.')
logging.critical('The program is unable to recover!')
2020-05-02 12:10:06,660 - DEBUG -Some debugging details.
2020-05-02 12:10:06,660 - INFO -The logging module is working
2020-05-02 12:10:06,660 - WARNING -An error message is about to be logged.
2020-05-02 12:10:06,660 - ERROR -An error has occurred.
2020-05-02 12:10:06,660 - CRITICAL -The program is unable to recover!
- level设置为ERROR级别时,只显示ERROR和CRITICAL日志
import logging
logging.basicConfig(level=logging.ERROR, format=' %(asctime)s - %(levelname)s -%(message)s')
logging.debug('Some debugging details.')
logging.info('The logging module is working')
logging.warning('An error message is about to be logged.')
logging.error('An error has occurred.')
logging.critical('The program is unable to recover!')
2020-05-02 12:10:59,120 - ERROR -An error has occurred.
2020-05-02 12:10:59,120 - CRITICAL -The program is unable to recover!
自定义log对象
def get_logger(logger_name, log_dir):
log_format = '[%(asctime)s] %(message)s'#定义日志输出格式
logger = logging.getLogger(logger_name)#创建日志对象
logger.setLevel(logging.DEBUG)# 启动日志级别
# 判断是否存在重复的logger对象,防止重复打印日志
if not logger.handlers:
#FileHandler 负责将日志写入文件
file_handler = logging.FileHandler(log_dir + '/' + 'result_' + logger_name + '.txt', encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(log_format))
# StreamHandler 负责将日志输出到控制台
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(logging.Formatter(log_format))
# logger绑定处理对象FileHandler,StreamHandler
# 将日志输出控制台并保存到文件中
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
return logger
由于当前研究需求,在上面代码中,我们将 file_handler.setLevel(logging.DEBUG),stream_handler.setLevel(logging.INFO),也就是将日志所有级别信息都写入到文件中,将INFO以上级别显示到控制台。
例如:
logger = get_logger(logger_name, log_dir)
logger.info('我想在控制台中看到你!')
logger.debug('我只想在文件中看到你!')
存在的问题
使用上面自定义的日志对象打印日志时,在pycharm控制台中显示的日志都是红色的,如果程序运行错误,引发异常(异常信息的也是红色),就很难与日志分辨出。有博客(https://www.cnblogs.com/mua9102/p/12261951.html
)修改了控制台文字颜色,但出现异常时,打印的异常信息的文字颜色也随着变化,这并不是一个很好的解决方式。
别人的解决方式:https://www.v2ex.com/t/602539
https://blog.csdn.net/xugexuge/article/details/87916020
后面两种方式我没有去尝试,不知道效果怎么样。
参考链接:
https://www.cnblogs.com/wwbplus/p/12001788.html
https://www.cnblogs.com/CJOKER/p/8295272.html
https://www.cnblogs.com/mua9102/p/12261951.html
https://www.v2ex.com/t/602539
https://blog.csdn.net/xugexuge/article/details/87916020