#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()