Python pit avoidance guide 02 - logging module log repeated printing problem

content

[TOC]

First, the problem is thrown

        Python's logging module is a powerful tool for printing logs during python usage. We can use the logger, handler, and formatter of the logging module to encapsulate our logs, and specify the path, format, and location of the log output. When declaring a logger, you can pass a string as the label of the logger. I always thought that this logger was designed in the design mode of a singleton object. As long as the label name is the same, the returned logger is the same. When printing the log, if you want to achieve log layering, define the following functions to encapsulate the log printing function (because the source code has been modified, in pseudocode form)

def print_log_info(msg):
    # Logger是我定义的一个类,用来封装日志打印的
    logger = Logger('INFO').getLogger()
    logger.info(msg)

        DDT is used in the test case to parameterize the test case. The key code is as follows:

    @data(*test_datas['test_add'])
    @unpack
    def test_add(self, *args, **kwargs):
        data_path, err_num, test_id, p1, p2, value = args
        result = Test(p1, p2).add()
        try:
            self.assertEqual(result, value, "在{err_num}行用例编号为{test_id}的测试中加法错误,请重新输入" .format(
                err_num = err_num,
                test_id = test_id
            ))
            utils.print_log_info("在{err_num}行用例编号为{test_id}的测试中加法测试成功".format(err_num = err_num,test_id = test_id))
        except AssertionError as err:
            err_str = traceback.format_exc()
            raise err

        After executing the test case, it is found that a test case has been printed multiple times, and the number of repeated prints has increased from 1 to n (the blogger is lazy, this is a screenshot of the problem in the source code).

log repeat printing

2. Problem solving

        At first, I always thought it was a bug of ddt. But then I defined a logger directly externally, and when I called this logger to print the log, I found that the log was not printed repeatedly, and when I accidentally declared the same logger twice, I found that the log printed two times. Second-rate. I began to think whether this is a problem with the logging module itself. Because in the code in Chapter 1, every time the log is printed, the print_log_info() function is required. Every time this function is called, a logger is declared. After each test case is executed, it is necessary to print the log and declare the logger again. Then the number of times of declaring the logger is 1 and increases to n . Is it similar to the situation where we repeated the log printing above? So consider that the problem is caused by the repeated declaration of logger. In order to verify the conjecture, make the following modifications to the code (the source code is too long, stick some key codes).

info_logger = Logger('INFO').get_logger()
error_logger = Logger('ERROR').get_logger()

def print_log_info(msg):
    '''
    打印测试用例执行的正常信息以及控制台日志
    :param msg:需要打印的信息
    :return:
    '''
    # 获取函数调用者的信息
    caller_module, msg_lineno = trace_caller(2)
    edit_msg = '[%s] : [%s]     %s' % (caller_module, msg_lineno, msg)
    print(edit_msg)
    info_logger.info(edit_msg)

def print_log_error(msg):
    '''
    用例出错时,打印错误日志以及控制台输出
    :param msg: 需要打印的信息
    :return:
    '''
    edit_msg = msg
    error_logger.error(edit_msg)

In the test case, the code for log printing is called in the same way as in Chapter 1, and the log is obtained as follows . The bug of repeated logs has been resolved:

[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [82]     在3行用例编号为test_add01的测试中加法测试成功
[2018-04-30 Monday 12:00:45] [ERROR] [MainThread:28980] 
文件:data\calculator.xls中测试用例出错
出错用例行:4,用例编号:test_add02
Traceback (most recent call last):
  File "C:\Users\Think\PycharmProjects\InterfaceFrame\src\test\case\testExample.py", line 80, in test_add
    test_id = test_id
  File "C:\Python33\lib\unittest\case.py", line 641, in assertEqual
    assertion_func(first, second, msg=msg)
  File "C:\Python33\lib\unittest\case.py", line 634, in _baseAssertEqual
    raise self.failureException(msg)
AssertionError: 3 != 4 : 在4行用例编号为test_add02的测试中加法错误,请重新输入

[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [82]     在5行用例编号为test_add03的测试中加法测试成功
[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [82]     在6行用例编号为test_add04的测试中加法测试成功
[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [160]     在15行用例编号为test_div01的测试中除法测试成功
[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [160]     在16行用例编号为test_div02的测试中除法测试成功
[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [160]     在17行用例编号为test_div03的测试中除法测试成功
[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [160]     在18行用例编号为test_div04的测试中除法测试成功
[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [135]     在11行用例编号为test_multi01的测试中乘法测试成功
[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [135]     在12行用例编号为test_multi02的测试中乘法测试成功
[2018-04-30 Monday 12:00:45] [INFO] [MainThread:28980] [src\test\case\testExample.py] : [135]     在13行用例编号为test_multi03的测试中乘法测试成功

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325053213&siteId=291194637