標籤:div creat ctime 檔案名稱 ima 調用 線程 同步 style
很多程式都有記錄日誌的需求,並且日誌中包含的資訊即有正常的程式訪問日誌,還可能有錯誤、警告等資訊輸出,python的logging模組提供了標準的日誌介面,你可以通過它儲存各種格式的日誌,logging的日誌可以分為 debug(), info(), warning(), error() and critical() 5個層級,下面我們看一下怎麼用。
一.最簡單用法
import logginglogging.debug(‘debug message‘)logging.info(‘info message‘)logging.warning(‘warning message‘)logging.error(‘error message‘)logging.critical(‘critical message‘)#WARNING:root:warning message#ERROR:root:error message#CRITICAL:root:critical message 預設只顯示warning以上的日誌
二.修改預設配置
import logging logging.basicConfig(level=logging.DEBUG, #這裡是日誌顯示的層級 format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘, #這裡是列印的格式,要顯示什麼內容 datefmt=‘%a, %d %b %Y %H:%M:%S‘, #答應日期的格式 filename=‘/tmp/test.log‘, #日誌儲存的位置,如果這裡不加filename,會以答應的形式顯示出來,而不會儲存 filemode=‘w‘) #這裡是w會重新覆蓋,a是追加 logging.debug(‘debug message‘) logging.info(‘info message‘) logging.warning(‘warning message‘) logging.error(‘error message‘) logging.critical(‘critical message‘)
1 format參數中可能用到的格式化串: 2 %(name)s Logger的名字 3 %(levelno)s 數字形式的記錄層級 4 %(levelname)s 文本形式的記錄層級 5 %(pathname)s 調用日誌輸出函數的模組的完整路徑名,可能沒有 6 %(filename)s 調用日誌輸出函數的模組的檔案名稱 7 %(module)s 調用日誌輸出函數的模組名 8 %(funcName)s 調用日誌輸出函數的函數名 9 %(lineno)d 調用日誌輸出函數的語句所在的程式碼10 %(created)f 目前時間,用UNIX標準的表示時間的浮 點數表示11 %(relativeCreated)d 輸出日誌資訊時的,自Logger建立以 來的毫秒數12 %(asctime)s 字串形式的目前時間。預設格式是 “2003-07-08 16:49:45,896”。逗號後面的是毫秒13 %(thread)d 線程ID。可能沒有14 %(threadName)s 線程名。可能沒有15 %(process)d 進程ID。可能沒有16 %(message)s使用者輸出的訊息
三.同步顯示
這裡出現一個問題,日誌只能要麼列印要麼儲存,只能選擇一個,我們改進一下
import logginglogger = logging.getLogger()# 建立一個handler,用於寫入記錄檔fh = logging.FileHandler(‘test.log‘)# 再建立一個handler,用於輸出到控制台ch = logging.StreamHandler()formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)fh.setFormatter(formatter)ch.setFormatter(formatter)logger.addHandler(fh) #logger對象可以添加多個fh和ch對象logger.addHandler(ch)
logger.setLevel(logging.Debug)logger.debug(‘logger debug message‘)logger.info(‘logger info message‘)logger.warning(‘logger warning message‘)logger.error(‘logger error message‘)logger.critical(‘logger critical message‘)
logging庫提供了多個組件:
Logger對象提供應用程式可直接使用的介面
Handler發送日誌到適當的目的地
Filter提供了過濾日誌資訊的方法
Formatter指定日誌顯示格式。
Python日誌logging模組