python自動化測試通過日志3分鐘定位bug
一、簡單使用
入門小案例
import logging logging.basicConfig(level=logging.DEBUG, #設(shè)置級別,根據(jù)等級顯示 format='%(asctime)s-[%(filename)s-->line:%(lineno)d]-%(levelname)s:% (message)s') # 設(shè)置輸出格式 logging.debug('This is a debug log') logging.info('This is a info log') logging.warning('This is a warning log') logging.error('This is a error log') logging.critical('This is a critical log')
日志級別
根據(jù)不同情況設(shè)置了五種日志等級,不同情況輸出不同等級的日志。
日志器設(shè)置的級別會過濾掉低于這個級別的日志
import logging logging.basicConfig(level=logging.WARNING, #設(shè)置級別,根據(jù)等級顯示 format='%(asctime)s-[%(filename)s-->line:%(lineno)d]-%(levelname)s:% (message)s') # 設(shè)置輸出格式 logging.debug('This is a debug log') logging.info('This is a info log') logging.warning('This is a warning log') logging.error('This is a error log') logging.critical('This is a critical log')
2020-09-11 17:39:26,667-WARNING-This is a warning log
2020-09-11 17:39:26,669-ERROR-This is a error log
2020-09-11 17:39:26,669-CRITICAL-This is a critical log
配置
basicConfig 方法支持一下關(guān)鍵字參數(shù)進行配置。
格式化規(guī)則
日志的輸出格式可以通過下面格式自由組合輸出
常用格式:%(asctime)s-[%(filename)s–>line:%(lineno)d]-%(levelname)s:% (message)s
import logging logging.basicConfig(level=logging.DEBUG, #設(shè)置級別,根據(jù)等級顯示 format='%(asctime)s-[%(filename)s-->line:%(lineno)d]-%(levelname)s:% (message)s') # 設(shè)置輸出格式 logging.debug('This is a debug log')
[DEBUG]-2020-09-11 17:36:50,125–4:This is a debug log
日志寫到文件
只需要配置 filename
參數(shù)即可
import logging logging.basicConfig( level=logging.WARNING, #設(shè)置級別,根據(jù)等級顯示 filename='example.log' format='%(asctime)s-[%(filename)s-->line:%(lineno)d]-%(levelname)s:% (message)s') # 設(shè)置輸出格式 logging.debug('This is a debug log') logging.info('This is a info log') logging.warning('This is a warning log') logging.error('This is a error log') logging.critical('This is a critical log')
注意,配置了 fielname 后,日志將不會輸出在控制臺。
二、高級用法
簡單的代碼通過 logging 直接使用即可,如果要深入使用需要按照面向?qū)ο蟮姆绞绞褂?logging。
日志組件
logging 模塊包含一下幾個組件。
步驟
1 創(chuàng)建日志記錄器
import logging # 第一步創(chuàng)建一個logger,用來產(chǎn)生日志 logger = logging.getLogger('%s_log' % __name__) logger.setLevel(logging.DEBUG) # 設(shè)置日志等級
通過 getLogger 這個方法可以創(chuàng)建一個日志記錄器,注意要給名字否則返回根日志記錄器。
通過 setLevel 設(shè)置日志記錄器的等級。
2 創(chuàng)建日志處理器
# 創(chuàng)建一個文本處理器用來將日志寫入到文件 file_handler = logging.FileHandler(filename='py34.log',encoding='utf-8')
file_handler.setLevel('WARNING') # 設(shè)置處理器的日志等級
# 創(chuàng)建一個控制臺處理器用來將日志輸出到控制臺 console_handler = logging.StreamHandler() console_handler.setLevel('INFO') # 設(shè)置控制臺處理器的日志等級
日志處理器就是將日志發(fā)送到指定的位置
FileHandler
將日志發(fā)送到文件
StreaHandler
將它可將日志記錄輸出發(fā)送到數(shù)據(jù)流例如 sys.stdout, sys.stderr 或任何文件類對象默認sys.stdout 即控制臺。
RotatingFileHandler
支持根據(jù)日志文件大小進行輪轉(zhuǎn)
TimedRotatingFileHandler
支持根據(jù)時間進行輪轉(zhuǎn)日志文件
更多詳情見官方文檔
(https://docs.python.org/zh-cn/3/library/logging.handlers.html?utm_source=testingpai.com#module-logging.handlers)
3 創(chuàng)建格式化器
formatter = logging.Formatter(fmt='%(levelname)s %(asctime)s [%(filename)s-->line:%(lineno)d]:%(message)s')
格式化器需要設(shè)置到處理器上
file_handler.setFormatter(formatter) console_handler.setFormatter(formatter)
4 創(chuàng)建過濾器
過濾器用來過濾指定日志。具體使用略,一般用不到。
詳情見官方文檔
(https://docs.python.org/zh-cn/3/howto/logging-cookbook.html?utm_source=testingpai.com#filters-contextual )
5 將處理器添加到記錄器上
logger.addHandler(file_handler) logger.addHandler(console_handler)
6 記錄日志
logger.info('This is a info')
2020-09-11 22:22:44,095-[–>line:1]-INFO:This is a info
logger.warning('This is a warning')
2020-09-11 22:23:20,337-[–>line:1]-WARNING:This is a warning
三、日志模塊封裝
功能分析
- 能夠自定義日志器名
- 能夠自定義日志文件名和路徑
- 能夠自定義日志文件編碼方式
- 能夠自定義日志格式
- 使用時間輪轉(zhuǎn)處理器,并能夠配置
封裝成函數(shù)
在 common 目錄下創(chuàng)建模塊 log_handler.py 在其中創(chuàng)建如下函數(shù)。
import logging from logging.handlers import TimedRotatingFileHandler def get_logger(name, filename, encoding='utf-8', fmt=None, when='d', interval=1, backup_count=7, debug=False): """ :param name: 日志器的名字 :param filename: 日志文件名(包含路徑) :param encoding: 字符編碼 :param fmt: 日志格式 :param when: 日志輪轉(zhuǎn)時間單位 :param interval: 間隔 :param backup_count: 日志文件個數(shù) :param debug: 調(diào)試模式 :return: """ logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) # 文件處理器的等級一般情況一定比控制臺要高 if debug: file_level = logging.DEBUG console_level = logging.DEBUG else: file_level = logging.WARNING console_level = logging.INFO if fmt is None: fmt = '%(levelname)s %(asctime)s [%(filename)s-->line:%(lineno)d]:%(message)s' file_handler = TimedRotatingFileHandler( filename=filename, when=when, interval=interval, backupCount=backup_count, encoding=encoding) file_handler.setLevel(file_level) console_handler = logging.StreamHandler() console_handler.setLevel(console_level) formatter = logging.Formatter(fmt=fmt) file_handler.setFormatter(formatter) console_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.addHandler(console_handler) return logger if __name__ == '__main__': log = get_logger(name='py41', filename='py41.log', debug=True, when='s') log.info('我是普通信息') import time time.sleep(3) log.warning('我是警告信息')
四、應(yīng)用到項目中
導(dǎo)入
日志器生成函數(shù)的導(dǎo)入不能像 Excel 數(shù)據(jù)讀取函數(shù)一樣,每個用例模塊里都導(dǎo)入一遍。因為它返回一個日志器對象,當多次調(diào)用日志器生成函數(shù),且日志器名稱相同時,會給同一個日志器添加多個日志處理器,從而出現(xiàn)重復(fù)記錄日志器的問題。
為了解決上面的問題,在 common 文件夾下創(chuàng)建一個名為 init.py 的文件,在 common 模塊被導(dǎo)入時會自動執(zhí)行這個文件里的代碼,且只會執(zhí)行一次。
在 init.py 文件編寫如下代碼:
from .log_handler import get_logger logger = get_logger('py41', 'py38.log')
那么在項目中的其他模塊中就可以通過如下代碼導(dǎo)入
from common import logger
從而可以保證在項目執(zhí)行過程中,get_logger 方法只會執(zhí)行一遍。
記錄日志
日志的作用是記錄程序的運行狀態(tài)和當程序出現(xiàn)問題時能提供定位分析錯誤的依據(jù)。
什么時候需要記錄日志,記錄什么日志,根據(jù)每個人對程序的理解,以及經(jīng)驗。
我們的項目中,在用例執(zhí)行的過程是核心,所以我們的日志也是圍繞著用例的執(zhí)行。
使用日志記錄每個用例的測試數(shù)據(jù),和測試結(jié)果,代碼如下:
... @list_data(*cases) def test_login(self, case): """ 登陸測試 """ logger.info('測試用例【{}】開始測試'.format(case['title'])) # 1. 測試數(shù)據(jù) # 傳入進來的case參數(shù) logger.info('測試用例【{}】的測試數(shù)據(jù)是:{}'.format(case['title'], case)) # 2. 測試步驟 res = login_check(case['username'], case['password']) logger.info('測試用例【{}】的測試結(jié)果是:{}'.format(case['title'], res)) # 3. 斷言 try: self.assertEqual(res, case['expect']) except AssertionError as e: logger.error('測試用例【{}】斷言失敗'.format(case['title'])) raise e else: logger.info('測試用例【{}】斷言成功'.format(case['title'])) finally: logger.info('測試用例【{}】測試結(jié)束')
以上就是python自動化測試通過日志3分鐘定位bug的詳細內(nèi)容,更多關(guān)于日志定位bug的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。