python常用模塊之logging模塊
阿新 • • 發佈:2017-08-20
tmp critical 結束 family logs code python for tool
---恢復內容開始---
一、logging模塊的作用以及兩種用法
logging模塊看名字就知道是用來寫日誌的,以前我們寫日誌需要自己往文件裏寫記錄信息,使用了logging之後我們只需要一次配置好,以後寫日誌的事情都不需要我們操心了,非常方便。logging模塊有兩種使用方法,一種是簡單的函數式,另一種是用logging對象的方式,對象的方式使用起來功能更全更靈活,所以使用最多的也是對象的方式。
二、函數式配置
import logging logging.basicConfig(level=logging.DEBUG, #不配置默認只輸出級別大於等於waring的日誌 format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘, datefmt=‘%a, %d %b %Y %H:%M:%S‘, filename=‘/tmp/test.log‘, filemode=‘w‘) logging.debug(‘debug message‘) logging.info(‘info message‘) logging.warning(‘warning message‘) logging.error(‘error message‘) logging.critical(‘critical message‘)
basicConfig可用參數
View Code
format參數可用的格式化字符串
View Code
三、logger對象配置
import logging def my_logger(filename,file=True,stream=True): ‘‘‘日誌函數‘‘‘ logger=logging.getLogger() #日誌對象 formatter = logging.Formatter(fmt=‘%(asctime)s -- %(message)s‘, datefmt=‘%d/%m/%Y %H:%M:%S‘) # 日誌格式 logger.setLevel(logging.DEBUG) # 日誌級別 if file: file_handler=logging.FileHandler(filename,encoding=‘utf-8‘) #文件流(文件操作符) file_handler.setFormatter(formatter) logger.addHandler(file_handler) if stream: stream_handler=logging.StreamHandler() #屏幕流(屏幕操作符) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) return logger logger=my_logger(‘log‘) logging.debug(‘出錯了‘)
---恢復內容結束---
python常用模塊之logging模塊