Python基礎(chǔ)之logging模塊知識(shí)總結(jié)
前言
logging模塊是Python內(nèi)置的標(biāo)準(zhǔn)模塊,主要用于輸出腳本運(yùn)行日志,可以設(shè)置輸出日志的等級(jí)、日志保存路徑等。
- 可以通過(guò)設(shè)置不同的日志等級(jí),在 release 版本中只輸出重要信息,而不顯示大量的調(diào)試信息
- logging 可以決定將信息輸出位置和內(nèi)容
- logging 線程更安全
一、日志級(jí)別
級(jí)別排序:CRITICAL > ERROR > WARNING > INFO > DEBUG
- debug : 打印全部日志,詳細(xì)信息,通常只出現(xiàn)在診斷問(wèn)題
- info : 打印info,warning,error,critical級(jí)別的日志,正常輸出
- warning : 打印warning,error,critical級(jí)別的日志,部分異常,不影響程序
- error : 打印error,critical級(jí)別的日志,影響程序部分功能
- critical : 打印critical級(jí)別,影響程序運(yùn)行
import logging # 引入logging模塊 # 將信息打印到控制臺(tái)上 logging.debug("debug") logging.info("info") logging.warning("warning") logging.error("error") logging.critical("critical") [root@zijie ~]# python log.py WARNING:root:warning ERROR:root:error CRITICAL:root:critical
默認(rèn)生成的root logger的level是logging.WARNING,低于該級(jí)別不輸出,如果要展示低于WARNING級(jí)別的內(nèi)容,可以引入logging.basicConfig指定日志級(jí)別logging.basicConfig(level=logging.DEBUG)
二、basicConfig
格式 | 描述 |
filename | 指定使用指定的文件名而不是 StreamHandler 創(chuàng)建 FileHandler。 |
filemode | 如果指定 filename,則以此模式打開(kāi)文件(‘r'、‘w'、‘a(chǎn)')。默認(rèn)為“a”。 |
format | 為處理程序使用指定的格式字符串。 |
datefmt | 使用 time.strftime() 所接受的指定日期/時(shí)間格式。 |
style | 如果指定了格式,則對(duì)格式字符串使用此樣式。'%' 用于 printf 樣式、'{' 用于 str.format()、'$' 用于 string。默認(rèn)為“%”。 |
level | 將根記錄器級(jí)別設(shè)置為指定的級(jí)別。默認(rèn)生成的 root logger 的 level 是 logging.WARNING,低于該級(jí)別的就不輸出了。級(jí)別排序:CRITICAL > ERROR > WARNING > INFO > DEBUG。(如果需要顯示所有級(jí)別的內(nèi)容,可將 level=logging.NOTSET) |
stream | 使用指定的流初始化 StreamHandler。注意,此參數(shù)與 filename 不兼容——如果兩者都存在,則會(huì)拋出 ValueError。 |
handlers | 如果指定,這應(yīng)該是已經(jīng)創(chuàng)建的處理程序的迭代,以便添加到根日志程序中。任何沒(méi)有格式化程序集的處理程序都將被分配給在此函數(shù)中創(chuàng)建的默認(rèn)格式化程序。注意,此參數(shù)與 filename 或 stream 不兼容——如果兩者都存在,則會(huì)拋出 ValueError。 |
import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s %(levelname)s %(message)s', datefmt='%a %d %b %Y %H:%M:%S', filename='xuehui.log', filemode='w') logging.info('This is a info.') logging.debug('This is a debug message.') logging.warning('This is a warning.')
三、日志寫(xiě)文件
import logging import os.path import time #創(chuàng)建logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) # 創(chuàng)建handler,用于寫(xiě)入日志文件 logdate = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) log_path = 'logs/' log_name = log_path + logdate + '.log' logfile = log_name fh = logging.FileHandler(logfile, mode='w') fh.setLevel(logging.DEBUG) # 定義輸出格式 formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s") fh.setFormatter(formatter) # 將logger添加到handler logger.addHandler(fh) # 日志 logger.debug('this is a logger debug message') logger.info('this is a logger info message') logger.warning('this is a logger warning message') logger.error('this is a logger error message') logger.critical('this is a logger critical message')
四、traceback記錄
import logging import os.path import time #創(chuàng)建logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) # 創(chuàng)建handler,用于寫(xiě)入日志文件 logdate = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) log_path = 'logs/' log_name = log_path + logdate + '.log' logfile = log_name fh = logging.FileHandler(logfile, mode='w') fh.setLevel(logging.DEBUG) # 定義輸出格式 formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s") fh.setFormatter(formatter) # 將logger添加到handler logger.addHandler(fh) # 日志 try: open('/data/exist', 'rb') except BaseException as e: logger.error('Failed to open file', exc_info=True)
到此這篇關(guān)于Python基礎(chǔ)之logging模塊知識(shí)總結(jié)的文章就介紹到這了,更多相關(guān)Python logging模塊內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pycharm與jupyter?lab/notebook結(jié)合使用方式
這篇文章主要介紹了pycharm與jupyter?lab/notebook結(jié)合使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06DataFrame中的object轉(zhuǎn)換成float的方法
下面小編就為大家分享一篇DataFrame中的object轉(zhuǎn)換成float的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04python將字典內(nèi)容存入mysql實(shí)例代碼
這篇文章主要介紹了python將字典內(nèi)容存入mysql實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01利用Python實(shí)現(xiàn)在同一網(wǎng)絡(luò)中的本地文件共享方法
今天小編就為大家分享一篇利用Python實(shí)現(xiàn)在同一網(wǎng)絡(luò)中的本地文件共享方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06使用keras根據(jù)層名稱來(lái)初始化網(wǎng)絡(luò)
這篇文章主要介紹了使用keras根據(jù)層名稱來(lái)初始化網(wǎng)絡(luò),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05pyqt實(shí)現(xiàn).ui文件批量轉(zhuǎn)換為對(duì)應(yīng).py文件腳本
今天小編就為大家分享一篇pyqt實(shí)現(xiàn).ui文件批量轉(zhuǎn)換為對(duì)應(yīng).py文件腳本,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06python numpy中array與pandas的DataFrame轉(zhuǎn)換方式
這篇文章主要介紹了python numpy中array與pandas的DataFrame轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07pytorch訓(xùn)練神經(jīng)網(wǎng)絡(luò)爆內(nèi)存的解決方案
這篇文章主要介紹了pytorch訓(xùn)練神經(jīng)網(wǎng)絡(luò)爆內(nèi)存的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05