Python's retrospective function call and log verbose printing

Source: Internet
Author: User

Directory

[TOC]

One, function call retrospective 1.1 reason

When the log is printed, the statements that print the logs are encapsulated in Print_log_info and print_log_error in order to achieve a hierarchical print of the logs. However, 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 position in logger.* in the Print_log_info and Print_log_error functions. So with the idea of tracing the function call, when printing the normal log, print the corresponding module name and the line number of the print log statement.

1.2 Using instance 2.2.1 Retrospective function call derivation

Call the Print_log_info function in a module and call the Trace_caller function in the Print_log_info function, the Trace_caller function is defined as follows:

import inspectdef trace_caller(laynum):    = inspect.currentframe()    =2)    print(cur_func_name)

The printing results are as follows:

[(<FrameObjectAt0x04dc2b70>,' C:\\Users\\Think\\pycharmprojects\\Interfaceframe\\src\\Utils\\utils.py ', +,' Trace_caller ', [' cur_func_name = Inspect.currentframe ()\ n',' cur_func_name = Inspect.getouterframes (Cur_func_name, 2)\ n'],1), (<FrameObjectAt0x04dd5380>,' C:\\Users\\Think\\pycharmprojects\\Interfaceframe\\src\\Utils\\utils.py ', +,' Print_log_info ', [' Print (msg) # in Htmltestrunner Print test report, use case execution succeeds, cannot trigger assertion, so need to print msg\ n',' caller_module, Msg_lineno = Trace_caller (2)\ n'],1), (<FrameObjectAt0x04b0c6b0>,' c:/users/think/pycharmprojects/interfaceframe/src/interfacetest.py ', -,' <module> ', ['\ n',' Utils.print_log_info ("Last Call to Tracecall function")\ n'],1)]

You can see that the print result is a list of elements in the list that are three tuples, and we focus on the 2nd element of each element, which is the path, number of lines of code, function name, and print statement of the module that calls print (Cur_func_name) and the previous call statement. So we need to take the value of cur_func_name corresponding element to achieve the desired effect.

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

The method described above can be traced back to the calling procedure of the function, but can only be traced back to statements such as Logger.info () of the print log. If you want to print the code for the wrong line, you need to take another approach. Which is the Traceback module.

2.1 Traceback Module Introduction

With the Traceback module, the detailed output of the error log can be implemented, but it needs to be used in conjunction with a try except statement, which can be used alone . The use cases are as follows:

class TestExample(unittest.TestCase):    def test_add(self):        = Test(22).add()        try:            self3"加法错误,请重新输入")            utils.print_log_info("测试成功")        exceptAssertionErroras err:            = 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 : 加法错误,请重新输入

Python's retrospective function call and log verbose printing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.