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.')
三、日志寫文件
import logging
import os.path
import time
#創(chuàng)建logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# 創(chuàng)建handler,用于寫入日志文件
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,用于寫入日志文件
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)文章
python模塊之subprocess模塊級(jí)方法的使用
這篇文章主要介紹了python模塊之subprocess模塊級(jí)方法的使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03
Flask框架實(shí)現(xiàn)debug模式下計(jì)算pin碼
pin碼也就是flask在開(kāi)啟debug模式下,進(jìn)行代碼調(diào)試模式的進(jìn)入密碼。本文為大家整理了Flask框架在debug模式下計(jì)算pin碼的方法,需要的可以參考一下2023-02-02
Pytorch測(cè)試神經(jīng)網(wǎng)絡(luò)時(shí)出現(xiàn) RuntimeError:的解決方案
這篇文章主要介紹了Pytorch測(cè)試神經(jīng)網(wǎng)絡(luò)時(shí)出現(xiàn) RuntimeError:的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05
Python獲取單個(gè)程序CPU使用情況趨勢(shì)圖
這篇文章主要介紹了Python獲取單個(gè)程序CPU使用情況趨勢(shì)圖,本文使用matplotlib將數(shù)據(jù)可視化,需要的朋友可以參考下2015-03-03
對(duì)python中的six.moves模塊的下載函數(shù)urlretrieve詳解
今天小編就為大家分享一篇對(duì)python中的six.moves模塊的下載函數(shù)urlretrieve詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
編寫Python腳本來(lái)獲取mp3文件tag信息的教程
這篇文章主要介紹了編寫Python腳本來(lái)獲取mp3文件tag信息的教程,代碼基于Python2.x,文中的注釋很詳細(xì),需要的朋友可以參考下2015-05-05
Python-for循環(huán)的內(nèi)部機(jī)制
這篇文章主要介紹了Python for循環(huán)的內(nèi)部機(jī)制,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
python3.7.2 tkinter entry框限定輸入數(shù)字的操作
這篇文章主要介紹了python3.7.2 tkinter entry框限定輸入數(shù)字的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05
python中圖片轉(zhuǎn)換為pdf實(shí)現(xiàn)方法
本文主要介紹了使用Python的Pillow分支和reportlab庫(kù)將圖片轉(zhuǎn)換為PDF文件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03

