Python's traceback function call and error log detailed printing

content

[TOC]

1. Function call traceback

1.1 Reasons

        When printing the log, in order to realize the hierarchical printing of the log, the statement of printing the log is encapsulated into print_log_info and print_log_error. But if you print the log directly through logger.* in the above function, the module name and line number in the log will always print the location in logger.* in the print_log_info and print_log_error functions. So with the idea of ​​tracing back the function call, when printing the normal log, print the corresponding module name and the line number of the log statement.

1.2 Example of use

2.2.1 Traceback function call deduction

        The print_log_info function is called in a module, and the trace_caller function is called in the print_log_info function. The trace_caller function is defined as follows:

import inspect

def trace_caller(laynum):
    cur_func_name = inspect.currentframe()
    cur_func_name = inspect.getouterframes(cur_func_name, 2)
    print(cur_func_name)

The print result is as follows:

[(<frame object at 0x04DC2B70>, 'C:\\Users\\Think\\PycharmProjects\\InterfaceFrame\\src\\utils\\utils.py', 19, 'trace_caller', ['    cur_func_name = inspect.currentframe()\n', '    cur_func_name = inspect.getouterframes(cur_func_name, 2)\n'], 1), 

(<frame object at 0x04DD5380>, 'C:\\Users\\Think\\PycharmProjects\\InterfaceFrame\\src\\utils\\utils.py', 62, 'print_log_info', ['        print(msg) # 在HTMLTestRunner打印测试报告,用例执行成功,不可能触发断言,所以需要打印msg\n', '        caller_module, msg_lineno = trace_caller(2)\n'], 1), 

(<frame object at 0x04B0C6B0>, 'C:/Users/Think/PycharmProjects/InterfaceFrame/src/InterfaceTest.py', 18, '<module>', ['\n', '    utils.print_log_info("最后调用tracecall函数")\n'], 1)]

        You can see that the print result is a list, and the elements in the list are three tuples. We focus on the second element of each element, and find that it is the path of the module that calls print(cur_func_name) and the upper-level calling statement, Lines of code, function names, and print statements. So we can achieve the effect we want by taking the value of the corresponding element of cur_func_name as needed.

1.2.2 Code Examples

def trace_caller(laynum):
    '''
    根据传递的laynum追溯函数调用者所在的模块、行数。目前只能在打印日志函数中使用
    :param laynum:追溯层数,由于在打印日志函数中调用本函数,追溯层数为2,
    :return:模块名, 打印日志所在行号
    '''
    cur_func_name = inspect.currentframe()
    cur_func_name = inspect.getouterframes(cur_func_name, 2)
    caller_module = cur_func_name[laynum][1][len(settings.PROJECT_DIR)+1:]
    msg_lineno = cur_func_name[laynum][2]
    return caller_module, msg_lineno

Second, the error detailed log information printing

        In the above way, it can be traced back to the calling process of the function, but at most it can only be traced back to the logger.info() and other statements that print the log. If you want to print the code of the error line, you need to use another way. That is, the traceback module

2.1 Introduction to traceback module

        Using the traceback module, you can achieve detailed output of the error log, but it needs to be used in conjunction with the try except statement, and an error will be reported when used alone . The use case is as follows:

class TestExample(unittest.TestCase):
    def test_add(self):
        result = Test(2, 2).add()
        try:
            self.assertEqual(result, 3, "加法错误,请重新输入")
            utils.print_log_info("测试成功")
        except AssertionError as err:
            err_str = traceback.format_exc()
            utils.print_log_error(err_str)
            raise err

print log

2018-04-25 Wednesday 21:48:47 - ERROR -MainThread:42464 - src\test\case\testExample.py : 16     Traceback (most recent call last):
  File "C:\Users\Think\PycharmProjects\InterfaceFrame\src\test\case\testExample.py", line 12, in test_add
    self.assertEqual(result, 3, "加法错误,请重新输入")
  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: 4 != 3 : 加法错误,请重新输入

Guess you like

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