python 包之 logging 日志處理教程
一、基本方法
默認(rèn)情況下日志打印只顯示大于等于 WARNING 級(jí)別的日志
FATAL:致命錯(cuò)誤
CRITICAL:特別糟糕的事情,如內(nèi)存耗盡、磁盤空間為空,一般很少使用
ERROR:發(fā)生錯(cuò)誤時(shí),如IO操作失敗或者連接問題
WARNING:發(fā)生很重要的事件,但是并不是錯(cuò)誤時(shí),如用戶登錄密碼錯(cuò)誤
INFO:處理請(qǐng)求或者狀態(tài)變化等日常事務(wù)
DEBUG:調(diào)試過程中使用DEBUG等級(jí),如算法中每個(gè)循環(huán)的中間狀態(tài)
import logging logging.debug('It is a debug') logging.info('It is a info') logging.warning('It is a warning') logging.error('It is a Error') logging.critical('It is a critical')
二、設(shè)置日志級(jí)別
import logging logging.basicConfig(level=logging.DEBUG) logging.debug('Python debug')
三、將信息記錄到文件
import logging logging.basicConfig(filename='logging.text', level=logging.DEBUG) logging.debug('It is a debug') logging.info('It is a info') logging.warning('It is a warning')
四、更改消息格式
%(levelno)s:打印日志級(jí)別的數(shù)值
%(levelname)s:打印日志級(jí)別的名稱
%(pathname)s:打印當(dāng)前執(zhí)行程序的路徑,其實(shí)就是sys.argv[0]
%(filename)s:打印當(dāng)前執(zhí)行程序名
%(funcName)s:打印日志的當(dāng)前函數(shù)
%(lineno)d:打印日志的當(dāng)前行號(hào)
%(asctime)s:打印日志的時(shí)間
%(thread)d:打印線程ID
%(threadName)s:打印線程名稱
%(process)d:打印進(jìn)程ID
%(message)s:打印日志信息
import logging logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logging.warning('is when this event was logged.')
五、配置日志
創(chuàng)建日志記錄配置文件并使用該 fileConfig() 功能讀取它
logging.conf 配置文件:
[loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=
使用
import logging import logging.config logging.config.fileConfig('logging.conf') logger = logging.getLogger('simpleExample') logging.debug('It is a debug') logging.info('It is a info') logging.warning('It is a warning') logging.error('It is a Error') logging.critical('It is a critical')
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請(qǐng)聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請(qǐng)聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。