函式式簡單配置
importlogging
logging.debug(
'debug message
')
logging.info(
'info message
')
logging.warning(
'warning message
')
logging.error(
'error message
')
logging.critical(
'critical message
')
預設情況下python的logging模組將日誌列印到了標準輸出中,且只顯示了大於等於warning級別的日誌,這說明預設的日誌級別設定為warning(日誌級別等級critical > error > warning > info > debug),預設的日誌格式為日誌級別:logger名稱:使用者輸出訊息。
靈活配置日誌級別,日誌格式,輸出位置:
importlogging
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
',
filemode='w'
)
logging.debug(
'debug message
')
logging.info(
'info message
')
logging.warning(
'warning message
')
logging.error(
'error message
')
logging.critical(
'critical message
')
配置引數:
logging.basicconfig()函式中可通過具體引數來更改logging模組預設行為,可用引數有:filename:用指定的檔名建立filedhandler,這樣日誌會被儲存在指定的檔案中。
filemode:檔案開啟方式,在指定了filename時使用這個引數,預設值為「a」還可指定為「w」。
format:指定handler使用的日誌顯示格式。
datefmt:指定日期時間格式。
level:設定rootlogger(後邊會講解具體概念)的日誌級別
stream:用指定的stream建立streamhandler。可以指定輸出到sys.stderr,sys.stdout或者檔案(f=open(『test.log』,』w』)),預設為sys.stderr。若同時列出了filename和stream兩個引數,則stream引數會被忽略。
format引數中可能用到的格式化串:
%(name)s logger的名字
%(levelno)s 數字形式的日誌級別
%(levelname)s 文字形式的日誌級別
%(pathname)s 呼叫日誌輸出函式的模組的完整路徑名,可能沒有
%(filename)s 呼叫日誌輸出函式的模組的檔名
%(module)s 呼叫日誌輸出函式的模組名
%(funcname)s 呼叫日誌輸出函式的函式名
%(lineno)d 呼叫日誌輸出函式的語句所在的**行
%(created)f 當前時間,用unix標準的表示時間的浮 點數表示
%(relativecreated)d 輸出日誌資訊時的,自logger建立以 來的毫秒數
%(asctime)s 字串形式的當前時間。預設格式是 「2003-07-08 16:49:45,896」。逗號後面的是毫秒
%(thread)d 執行緒id。可能沒有
%(threadname)s 執行緒名。可能沒有
%(process)d 程序id。可能沒有
%(message)s使用者輸出的訊息
logger物件配置
importlogging
logger =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.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。logger物件提**用程式可直接使用的介面,handler傳送日誌到適當的目的地,filter提供了過濾日誌資訊的方法,formatter指定日誌顯示格式。另外,可以通過:logger.setlevel(logging.debug)設定級別,當然,也可以通過
fh.setlevel(logging.debug)單對檔案流設定某個級別。
configparser模組,logging模組
configparser模組 import configparser ret configparser.configparser ret a ret b ret c with open file w as f ret.write f 自動生成檔案 a 1 2 3 4 b 5 6 c 7 8 按照字典...
詳解Python中的日誌模組logging
許多應用程式中都會有日誌模組,用於記錄系統在執行過程中的一些關鍵資訊,以便於對系統的執行狀況進行跟蹤。在.net平台中,有非常著名的第三方開源日誌元件log4net,c 中,有人們熟悉的log4cpp,而在python中,我們不需要第三方的日誌元件,因為它已經為我們提供了簡單易用 且功能強大的日誌模...
day21 shutil模組和logging模組
一 shutil模組 copy2函式 複製檔案 copytree 拷貝整個目錄 rmtree 刪除整個目錄 move 移動檔案 eg shutil.copy d test testfile.txt d test testfilebak.txt 複製乙份檔案 shutil.move d test te...