程序员Python语言与信息数据获取和机器学习机器学习

python logging模块的简单使用(二)

2017-09-17  本文已影响128人  迈阿密小白

前提

上一篇 文章,介绍了官方对logging模块的简单介绍及一些基础语法,这篇文章主要介绍将logging用到接口测试、UI自动化测试中,活学活用,话不多说直接上代码

代码介绍

创建一个logger.py文件来封装日志文件的读取

#coding=utf-8
#author='Shichao-Dong'

import time,logging

class log():
    def __init__(self):
        filename = 'example'+''.join(time.strftime('%Y%m%d'))+''.join('.log') #设置log名
        self.logname = filename
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        #设置日志输出格式
        self.formatter = logging.Formatter('[%(asctime)s] - [%(levelname)s] - %(message)s')

第一部分定义log的文件名以及log输出的格式,这边在上一篇文章已经介绍过了

    def output(self,level,message):
        '''
        :param level: 日志等级
        :param message: 日志需要打印的信息
        :return:
        '''

        #send logging output to a disk file
        fh = logging.FileHandler(self.logname,'a')
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(self.formatter)
        self.logger.addHandler(fh)

        #send logging output to streams
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(self.formatter)
        self.logger.addHandler(ch)

        if level == 'info':
            self.logger.info(message)
        elif level =='debug':
            self.logger.debug(message)
        elif level =='warn':
            self.logger.warn(message)
        elif level =='error':
            self.logger.error(message)

        self.logger.removeHandler(fh)
        self.logger.removeHandler(ch)

        fh.close()

第二部分主要是创建handlers,其中:
StreamHandler在控制台输出log
FileHandler 向文件中输出log并生成一个log文件,文件在第一部分已经定义过,
这边有两个参数一个是日志等级,一个是日志输出的内容

def info(self,message):
        self.output('info',message)

    def debug(self,message):
        self.output('debug',message)

    def warn(self,message):
        self.output('warn',message)

    def error(self,message):
        self.output('error',message)

第三部分主要定义各个等级的日志
最终运行的实际效果如下所示:控制台有打印日志,同时文件同级目录下会生成一个日志文件

    log = log()
    log.info(u'开始测试')
    log.debug('this is debug')
    log.warn('this is warn')
    log.error('this is error')

控制台输出:


output1.png

log文件显示:


output2.png

在自动化测试中的使用

先看一个框架图:

框架.png

这是一个简单的测试框架,其中:
logs文件用来存放日志
public用来定义一些公共方法
runtest用来运行测试用例,生成的报告也可以存放在该路径
screenshoot用来存放用例执行失败时的截图
visit是一个测试场景或者一个模块的测试用例,下面还有其他模块比如product,customer等,这边截图就不放上来
在写测试用例的时候,只需要将logger.py文件导入到用例中,后面再需要记录日志的地方加上

log.info('this is info')
log.error('this is error')

测试结束后就会生成对应的log文件

上一篇下一篇

猜你喜欢

热点阅读