python学习笔记(日志系统实现)

 

博主今天在自己的接口自动化框架中添加了日志系统

基于python自带的logging库、包括日志主函数、生成日志文件:

 1 # -*- coding: utf-8 -*-
 2 # 日志系统
 3 # 时间:2017-08-31
 4 # 姓名:xx
 5 
 6 import logging
 7 import os
 8 from datetime import datetime
 9 
10 
11 class MainLog:
12     def __init__(self):
13         pass
14 
15     @staticmethod
16     def getLog():
17         logging.basicConfig(
18             # filename=MainLog.logTxt(),    # 日志输出到文件
19             level=logging.DEBUG,
20             format="%(asctime)s - %(levelname)s - %(message)s",
21             datefmt="%Y-%m-%d %H:%M:%S",
22         )
23         return logging
24 
25     @staticmethod
26     def logTxt():
27         today_name = datetime.today().strftime("%Y%m%d")
28         log_name = datetime.today().strftime("%Y%m%d%H%M%S") + ".txt"
29         # 新建当天的文件夹路径
30         path = "F:\\Logs\\" + today_name + "\\"
31         if os.path.exists(path):
32             pass
33         else:
34             os.makedirs(path)
35         # 日志文件路径名称
36         file_path = path + log_name
37         return file_path
 1 # -*- coding: utf_8 -*-
 2 # 基础接口请求方法
 3 # 时间:2017-08-31
 4 import requests
 5 from requests.exceptions import ReadTimeout, ConnectionError, RequestException
 6 from Log.main_log import MainLog
 7 
 8 
 9 class MainResponse:
10     def __init__(self):
11         pass
12 
13     @staticmethod
14     def mainPost(url=None, params=None, json=None):
15         u"""
16         url: 接口请求的url
17         params: 接口请求的请求头
18         json: 接口请求的json
19         """
20         logger = MainLog.getLog()
21         try:
22             response = requests.post(url=url, params=params, json=json, timeout=10)
23             code = response.status_code
24             text = response.text
25             logger.debug(u"接口请求地址:")
26             logger.debug(url)
27             logger.debug(u"接口请求头:")
28             logger.debug(params)
29             logger.debug(u"接口请求参数:")
30             logger.debug(json)
31             logger.debug(u"接口请求返回码:")
32             logger.debug(code)
33             logger.debug(u"接口返回信息:")
34             logger.debug(text)
35             return text
36         except ReadTimeout:
37             logger.error(u"请求超时")
38         except ConnectionError:
39             logger.error(u"请求连接错误")
40         except RequestException:
41             logger.error(u"返回错误")

然后在自己封装的post请求中把日志格式加进去

DEBUG级别的是普通的内容

ERROR级别的是错误场景

最后在unittest框架中执行自动化用例、生成测试报告:

 

posted on 2017-08-31 20:36  堕落的伊丝莉  阅读(673)  评论(0编辑  收藏  举报