Python interface automated testing - logging logs

Log levels of the logging module: There are a total of 5 log levels from low to high as follows. The purpose is that when you assign a logger to a python function, you need to mark the log level yourself (will be used later)

debug (debug level): the lowest severity level and the most detailed log information, often used for problem diagnosis

info (minor level): The severity is second only to DEBUG, and the information details are also second only to DEBUG. Usually only key node information is recorded to confirm whether everything is working as we expected.

warning (warning level): Information logged when something unexpected happens (for example, disk free space is low), but the application is still running normally.

error (error level): Information logged when some functionality is not functioning properly due to a more serious problem.

critical (serious error level): information recorded when a serious error occurs that prevents the application from continuing to run.

The four major components of python-logging:

logger: logger, provides an interface for direct use by application code

handler: processor, used to send log records to the specified destination

formater: Formatter, used to define the output format of log information

filter: filter, filter log content

Write your first logger:

import logging

# 创建日志器: logging_name(日志器名,可以随便写),一个日志器可以有多个处理器, 并且每个处理器都可以有自己不同的格式器及过滤器
logger = logging.getLogger('logging_name')

# 设置日志输出等级,如果不设置则默认warning级别,也就是只有日志级别为warning或则以上时,才会打印日志,否则不会打印,一般来说需要设置成 debug 打印全部级别
logger.setLevel(logging.DEBUG)

# 创建处理器:
sh = logging.StreamHandler()

# 创建格式器: 日志时间%(asctime)s、文件名%(filename)s、行%(lineno)d、日志级别%(levelname)s、事件内容%(message)s
ft = logging.Formatter(fmt='日志时间: %(asctime)s\n文件名: %(filename)s 在第%(lineno)d行\n日志级别: %(levelname)s\n事件内容: %('
                           'message)s\n', datefmt='%Y年%m月%d日 %X')

# 在日志器中添加处理器
logger.addHandler(sh)

# 将设置好的格式器添加到处理器中
sh.setFormatter(ft)

# 输出日志信息,事件内容需要自己写,这条代码放在哪个文件, 错误定位就会显示在哪个文件
logger.debug('事件内容')

执行结果>>>
日志时间: 2023年02月05日 17:52:25
文件名: test_003.py 在第23行
日志级别: DEBUG
事件内容: 事件内容

The above illustrates the simple creation of a logger. The following demonstrates how to integrate the logger into automation.

First, we need to encapsulate the above "linear logger", as follows, I encapsulate it into a class, and then remove the line of code that outputs the log, otherwise the error will always be located in the log function file.

import logging


class Log:
    def getlog(self):

        # 创建日志器: logging_name(日志器名,可以随便写),一个日志器可以有多个处理器, 并且每个处理器都可以有自己不同的格式器及过滤器
        logger = logging.getLogger('logging_name')

        # 设置日志输出等级,如果不设置则默认warning级别,也就是只有日志级别为warning或则以上时,才会打印日志,否则不会打印,一般来说需要设置成 debug 打印全部级别
        logger.setLevel(logging.DEBUG)

        # 创建处理器:
        sh = logging.StreamHandler()

        # 创建格式器: 日志时间%(asctime)s、文件名%(filename)s、行%(lineno)d、日志级别%(levelname)s、事件内容%(message)s
        ft = logging.Formatter(fmt='日志时间: %(asctime)s\n文件名: %(filename)s 在第%(lineno)d行\n日志级别: %(levelname)s\n事件内容: %('
                                   'message)s\n', datefmt='%Y年%m月%d日 %X')

        # 在日志器中添加处理器
        logger.addHandler(sh)

        # 将设置好的格式器添加到处理器中
        sh.setFormatter(ft)

        return logger

As follows, I defined a test case and a public function 

def comparison(da):
    if da in '中文':
        return '函数执行成功,是中文'

# 测试模块
class TestC:
    # 测试用例
    def test001(self):
        print(comparison(1))

TestC().test001()

comparison, the function of the public function is to execute successfully if you enter "Chinese", and an error will be reported if you enter numbers.

def comparison(da):
    if da in '中文':
        return '函数执行成功,是中文'

# 测试模块
class TestC:
    # 测试用例
    def test001(self):
        print(comparison(1))

TestC().test001()

My idea is very simple, I just want to add the logger to the comparison function. If an error is reported, I want to know its error time, error file, error line, error level, and error content. If successful, I also need to know its time, file, line, level, and content. How to achieve? It's very simple, just transform the public function, as follows

# 首先将日志类函数导入
from test_001 import Log

def comparison(da):

    try:
        if da in '中文':
            # 成功的情况
            Log().getlog().info(f'正在执行 comparison 函数,暂无错误,对比值为{da}:中文')
            return '函数执行成功,是中文'
    except Exception:
        # 报错的情况
        Log().getlog().error(f'正在执行 comparison 函数,类型对比错误,对比值为{da}:中文')

# 测试模块
class TestC:
    # 测试用例
    def test001(self):
        comparison(1)


TestC().test001()


执行结果>>>
日志时间: 2023年02月05日 17:49:29
文件名: test_002.py 在第13行
日志级别: ERROR
事件内容: 正在执行 comparison 函数,类型对比错误,对比值为1:中文

logging - log written to txt file

As shown below, the only change is the code marked in orange

import logging


class Log:
    # 日志器
    def getlog(self, log_path):
        """
        :param log_path: 日志输入文件所在路径,建议文件以txt格式,如果文件不存在则自动新建
        :return:
        """

        # 创建日志器: logging_name(日志器名,可以随便写)
        logger = logging.getLogger('logging_name')

        # 过滤器:设置日志输出等级
        logger.setLevel(logging.DEBUG)

        # 创建格式器: 日志时间%(asctime)s、文件名%(filename)s、行%(lineno)d、日志级别%(levelname)s、事件内容%(message)s
        ft = logging.Formatter(fmt='日志时间: %(asctime)s\n文件名: %(filename)s 在第%(lineno)d行\n日志级别: %(levelname)s\n事件内容: %('
                                   'message)s\n', datefmt='%Y年%m月%d日 %X')

        # 设置文件格式
        handler = logging.FileHandler(log_path, encoding='UTF-8')
        handler.setFormatter(ft)

        # 在日志器中添加处理器
        logger.addHandler(handler)

        # 将日志输出器返回。logger日志器、log_level日志级别、content日志内容
        return logger

How to use it? As follows, the orange changed part

# 首先将日志类函数导入
from test_001 import Log


def comparison(da):
    try:
        if da in '中文':
            # log.txt:日志文件的路径,如果过没有该文件则自动新增
            Log().getlog('log.txt').debug(f'正在执行 comparison 函数,暂无错误,对比值为{da}:中文')
            return '函数执行成功,是中文'
    except Exception:
        # log.txt:日志文件的路径,如果过没有该文件则自动新增
        Log().getlog('log.txt').debug(f'正在执行 comparison 函数,类型错误,对比值为{da}:中文')


# 测试模块
class TestC:
    # 测试用例
    def test001(self):
        comparison(1)


TestC().test001()

After execution, there is no log output content in the console, and the content is output to the log.txt file, as follows

Summarize:

The above are the instructions for using the log module - logging. The difficulty of the log module is not in the code, but in the log setting point, that is, where is the best place to implant the log. The implantation function of the logger is best to be public. And the places where errors are most likely to be reported, just like the places where surveillance cameras are most likely to have troubles, so that problems can be quickly located.

In fact, in my projects, the function of writing logs to files is generally not used. I just input and display it directly on the console. If a certain use case fails to execute, we usually read the test report first, and then execute the failed use case separately. to debug. Because the test framework is set up by myself, you can know the cause by looking at the console when an error is reported. So under what circumstances will logs be used? When your framework is used by many people, or when colleagues who are not familiar with the interface framework use it, they usually don’t know where the error is reported. At this time, they will look at the log report, but under the premise, your log must be complete. That's fine, otherwise they won't know what's wrong

Finally, I would like to thank everyone who read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software testing interview applet

A software test question bank that has been used by millions of people! ! ! Who is who knows! ! ! The most comprehensive interview test mini program on the Internet, you can use your mobile phone to answer questions, take the subway, bus, and roll it up!

Covers the following interview question sections:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. Web, app, interface automation, 7. Performance testing, 8. Programming basics, 9. HR interview questions, 10. Open test questions, 11. Security testing, 12. Computer basics

Information acquisition method:

Guess you like

Origin blog.csdn.net/myh919/article/details/132736868