摘錄自python logging模塊官方教程
記錄日志到文件
對(duì)于簡(jiǎn)單的日志使用來(lái)說(shuō)日志功能提供了一系列便利的函數(shù)。它們是?debug(),info(),warning(),error()?和?critical()。
將日志事件記錄到文件中:
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
對(duì)?basicConfig()?的調(diào)用應(yīng)該在?debug()?,?info()?等的前面。因?yàn)樗辉O(shè)計(jì)為一次性的配置,只有第一次調(diào)用會(huì)進(jìn)行操作,隨后的調(diào)用不會(huì)產(chǎn)生有效操作。如果你希望每次運(yùn)行重新開(kāi)始,而不是記住先前運(yùn)行的消息,則可以通過(guò)將上例中的調(diào)用更改為來(lái)指定?filemode?參數(shù):
logging.basicConfig(filename='example.log',filemode='w',level=logging.DEBUG)
記錄變量數(shù)據(jù)
要記錄變量數(shù)據(jù),請(qǐng)使用格式字符串作為事件描述消息,并將變量數(shù)據(jù)作為參數(shù)附加。 例如:
import logging
logging.warning('%s before you %s','Look','leap!')
更改顯示消息的格式
import logging
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
在消息中顯示日期/時(shí)間
要顯示事件的日期和時(shí)間,你可以在格式字符串中放置 '%(asctime)s'
importlogging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')