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