#coding:utf-8
import logging
class TestLog(object):
'''
封裝后的logging
'''
def __init__(self , logger = None):
'''
指定保存日志的文件路徑,日志級別,以及調用文件
將日志存入到指定的文件中
'''
# 創建一個logger
self.logger = logging.getLogger(logger)
self.logger.setLevel(logging.DEBUG)
# 創建一個handler,用於寫入日志文件
self.log_time = time.strftime("%Y_%m_%d_")
self.log_path = "D:\\python\\workspace\\pythontest\\log\\"
self.log_name = self.log_path + self.log_time + 'test.log'
fh = logging.FileHandler(self.log_name, 'a') # 追加模式 這個是python2的
# fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8') # 這個是python3的
fh.setLevel(logging.INFO)
# 再創建一個handler,用於輸出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# 定義handler的輸出格式
formatter = logging.Formatter('[%(asctime)s] %(filename)s->%(funcName)s line:%(lineno)d [%(levelname)s]%(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# 給logger添加handler
self.logger.addHandler(fh)
self.logger.addHandler(ch)
# 添加下面一句,在記錄日志之后移除句柄
# self.logger.removeHandler(ch)
# self.logger.removeHandler(fh)
# 關閉打開的文件
fh.close()
ch.close()
def getlog(self):
return self.logger
封裝后的logging代碼中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: 打印日志信息
封裝python自帶的logging類,向Logger類中傳用例名稱,用法
log = Logger().getlog() #放在class上面
class ClassName()
log.info("log message")
結果:
[2018-01-17 22:45:05,447] test_mainrun.py test_run_mail line:31 [INFO]截圖保存成功,全路徑
具體用法:


代碼如下:
1 #coding:utf-8 5 from selenium import webdriver 6 import unittest 7 from pythontest.commlib.baselib import TestLog 8 #自定義公共模塊 9 10 log = TestLog().getlog() 11 class testcals(unittest.TestCase): 12 u'''【調用】''' 13 def setUp(self): 14 self.driver = webdriver.Firefox() 15 self.base = Screen(self.driver) # 實例化自定義類commlib.baselib 16 17 def login(self): 18 url_login = "http://www.baidu.com" 19 self.driver.get(url_login) 20 21 def test_01_run_mail(self): 22 try: 26 self.login()28 log.info(self.img) 29 except Exception as msg: 30 log.error("異常原因 [ %s ]" % msg)32 log.error(self.img) 33 raise 34 35 def test_02_case(self): 36 u'''【test_case】''' 37 log.error("首頁error 日志") 38 log.debug("訂單頁debug 日志") 39 log.info("活動頁info 日志") 40 log.critical("支付critical 日志") 4 43 44 def tearDown(self): 45 self.driver.quit() 46 47 if __name__ == "__main__": 48 unittest.main()

