Python——日誌模組(logging)
阿新 • • 發佈:2019-01-02
一、日誌說明
日誌是跟蹤軟體執行時所發生的事件的一種方法。軟體開發者在程式碼中呼叫日誌函式,表明發生了特定的事件。事件由描述性訊息描述,該描述性訊息可以可選地包含可變資料(即,對於事件的每次出現都潛在地不同的資料)。事件還具有開發者歸因於事件的重要性;重要性也可以稱為級別或嚴重性。
二、列印到控制檯
import logging logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s', level=logging.DEBUG) logging.debug('debug 資訊') logging.info('info 資訊') logging.warning('warning 資訊') logging.error('error 資訊') logging.critical('critial 資訊')
日誌級別: debug < info < warning < error < critical logging.debug('debug級別,最低級別,一般開發人員用來列印一些除錯資訊') logging.info('info級別,正常輸出資訊,一般用來列印一些正常的操作') logging.warning('waring級別,一般用來列印警資訊') logging.error('error級別,一般用來列印一些錯誤資訊') logging.critical('critical 級別,一般用來列印一些致命的錯誤資訊,等級最高')
三、將日誌寫入日誌中
logging.basicConfig(level=logging.DEBUG,#控制檯列印的日誌級別 filename='new.log', filemode='a',##模式,有w和a,w就是寫模式,每次都會重新寫日誌,覆蓋之前的日誌 #a是追加模式,預設如果不寫的話,就是追加模式 format= '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s' #日誌格式 )
四、程式碼例項
import logging from logging import handlers class Logger(object): level_relations = { 'debug':logging.DEBUG, 'info':logging.INFO, 'warning':logging.WARNING, 'error':logging.ERROR, 'crit':logging.CRITICAL }#日誌級別關係對映 def __init__(self,filename,level='info',when='D',backCount=3,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'): self.logger = logging.getLogger(filename) format_str = logging.Formatter(fmt)#設定日誌格式 self.logger.setLevel(self.level_relations.get(level))#設定日誌級別 sh = logging.StreamHandler()#往螢幕上輸出 sh.setFormatter(format_str) #設定螢幕上顯示的格式 th = handlers.TimedRotatingFileHandler(filename=filename,when=when,backupCount=backCount,encoding='utf-8')#往檔案裡寫入#指定間隔時間自動生成檔案的處理器 #例項化TimedRotatingFileHandler #interval是時間間隔,backupCount是備份檔案的個數,如果超過這個個數,就會自動刪除,when是間隔的時間單位,單位有以下幾種: # S 秒 # M 分 # H 小時、 # D 天、 # W 每星期(interval==0時代表星期一) # midnight 每天凌晨 th.setFormatter(format_str)#設定檔案裡寫入的格式 self.logger.addHandler(sh) #把物件加到logger裡 self.logger.addHandler(th) if __name__ == '__main__': log = Logger('all.log',level='debug') log.logger.debug('debug') log.logger.info('info') log.logger.warning('警告') log.logger.error('報錯') log.logger.critical('嚴重') Logger('error.log', level='error').logger.error('error')