小編給大家分享一下Python中精選的logging模塊是什么,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討方法吧!
用Python寫代碼的時候,在想看的地方寫個print(xx) 就能在控制臺上顯示打印信息,這樣子就能知道它是什么了,但是當我需要看大量的地方或者在一個文件中查看的時候,這時候print就不大方便了,所以Python引入了logging模塊來記錄想要的信息。
1 日志級別
import logging # 引入logging模塊 # 將信息打印到控制臺上 logging.debug(u"debug") logging.info(u"info") logging.warning(u"warning") logging.error(u"error") logging.critical(u"critical")
回顯:

上面可以看到只有后面三個能打印出來
默認生成的root logger的level是logging.WARNING,低于該級別的就不輸出了
級別排序:CRITICAL > ERROR > WARNING > INFO > DEBUG
debug : 打印全部的日志,詳細的信息,通常只出現在診斷問題上
info : 打印info,warning,error,critical級別的日志,確認一切按預期運行
warning : 打印warning,error,critical級別的日志,一個跡象表明,一些意想不到的事情發生了,或表明一些問題在不久的將來(例如。磁盤空間低”),這個軟件還能按預期工作
error : 打印error,critical級別的日志,更嚴重的問題,軟件沒能執行一些功能
critical : 打印critical級別,一個嚴重的錯誤,這表明程序本身可能無法繼續運行
這時候,如果需要顯示低于WARNING級別的內容,可以引入NOTSET級別來顯示:
import logging # 引入logging模塊 logging.basicConfig(level=logging.NOTSET) # 設置日志級別 logging.debug(u"如果設置了日志級別為NOTSET,那么這里可以采取debug、info的級別的內容也可以顯示在控制臺上了")
回顯:
2 部分名詞解釋
print也可以輸入日志,logging相對print來說更好控制輸出在哪個地方,怎么輸出及控制消息級別來過濾掉那些不需要的信息。
Logging.Formatter:這個類配置了日志的格式,在里面自定義設置日期和時間,輸出日志的時候將會按照設置的格式顯示內容。
Logging.Logger:Logger是Logging模塊的主體,進行以下三項工作:
1、為程序提供記錄日志的接口
2、判斷日志所處級別,并判斷是否要過濾
3、根據其日志級別將該條日志分發給不同handler
常用函數有:
Logger.setLevel() 設置日志級別
Logger.addHandler() 和 Logger.removeHandler() 添加和刪除一個Handler
Logger.addFilter() 添加一個Filter,過濾作用
Logging.Handler:Handler基于日志級別對日志進行分發,如設置為WARNING級別的Handler只會處理WARNING及以上級別的日志。
3 日志輸出-控制臺
import logging # 引入logging模塊
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函數對日志的輸出格式及方式做相關配置
# 由于日志基本配置中級別設置為DEBUG,所以一下打印信息將會全部顯示在控制臺上
logging.info('this is a loggging info message')
logging.debug('this is a loggging debug message')
logging.warning('this is loggging a warning message')
logging.error('this is an loggging error message')
logging.critical('this is a loggging critical message')上面代碼通過logging.basicConfig函數進行配置了日志級別和日志內容輸出格式;因為級別為DEBUG,所以會將DEBUG級別以上的信息都輸出顯示再控制臺上。
回顯:
4 日志輸出-文件
import logging # 引入logging模塊
import os
import time
# 第一步,創建一個logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log等級總開關
# 第二步,創建一個handler,用于寫入日志文件
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
log_path = os.path.dirname(os.getcwd()) + '/Logs/'
# 如果日志目錄不存在,就創建
if not os.path.exists(log_path):
os.mkdir(log_path)
log_name = log_path + rq + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG) # 輸出到file的log等級的開關
# 第三步,定義handler的輸出格式
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')回顯(打開同一目錄下生成的文件):

文件內容:
5 日志輸出-控制臺和文件
只要在輸入到日志中的第三步和第四步插入一個handler輸出到控制臺:
# 創建一個handler,用于輸出到控制臺 ch = logging.StreamHandler() ch.setLevel(logging.WARNING) # 輸出到console的log等級的開關 # 第三步和第四步分別加入以下代碼即可 ch.setFormatter(formatter) logger.addHandler(ch)
6 format常用格式說明
%(levelno)s: 打印日志級別的數值
%(levelname)s: 打印日志級別名稱
%(pathname)s: 打印當前執行程序的路徑,其實就是sys.argv[0]
%(filename)s: 打印當前執行程序名
%(funcName)s: 打印日志的當前函數
%(lineno)d: 打印日志的當前行號
%(asctime)s: 打印日志的時間
%(thread)d: 打印線程ID
%(threadName)s: 打印線程名稱
%(process)d: 打印進程ID
%(message)s: 打印日志信息
7 捕捉異常,用traceback記錄
import os.path
import time
import logging
# 創建一個logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log等級總開關
# 創建一個handler,用于寫入日志文件
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
log_path = os.path.dirname(os.getcwd()) + '/Logs/'
# 如果日志目錄不存在,就創建
if not os.path.exists(log_path):
os.mkdir(log_path)
log_name = log_path + rq + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG) # 輸出到file的log等級的開關
# 定義handler的輸出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
# 使用logger.XX來記錄錯誤,這里的"error"可以根據所需要的級別進行修改
try:
open('/path/to/does/not/exist', 'rb')
except (SystemExit, KeyboardInterrupt):
raise
except Exception as e:
logger.error('Failed to open file', exc_info=True)回顯(存儲在文件中):
如果需要將日志不上報錯誤,僅記錄,可以將exc_info=False,回顯如下:
8 多模塊調用logging,日志輸出順序
warning_output.py
import logging def write_warning(): logging.warning(u"記錄文件warning_output.py的日志")
error_output.py
import logging def write_error(): logging.error(u"記錄文件error_output.py的日志")
main.py
import logging import warning_output import error_output def write_critical(): logging.critical(u"記錄文件main.py的日志") warning_output.write_warning() # 調用warning_output文件中write_warning方法 write_critical() error_output.write_error() # 調用error_output文件中write_error方法
回顯:

從上面來看,日志的輸出順序和模塊執行順序是一致的。
9 日志滾動和過期刪除
# coding:utf-8
import logging
import time
import re
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
def backroll():
# 日志打印格式
log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
formatter = logging.Formatter(log_fmt)
# 創建TimedRotatingFileHandler對象
log_file_handler = TimedRotatingFileHandler(filename="ds_update", when="M", interval=2, backupCount=2)
# log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
# log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
log_file_handler.setFormatter(formatter)
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
log.addHandler(log_file_handler)
# 循環打印日志
log_content = "test log"
count = 0
while count < 30:
log.error(log_content)
time.sleep(20)
count = count + 1
log.removeHandler(log_file_handler)
if __name__ == "__main__":
backroll()filename:日志文件名的prefix;
when:是一個字符串,用于描述滾動周期的基本單位,字符串的值及意義如下:
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight
interval: 滾動周期,單位有when指定,比如:when=’D’,interval=1,表示每天產生一個日志文件
backupCount: 表示日志文件的保留個數
看完了這篇文章,相信你對Python中精選的logging模塊是什么有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。