Enrich your log information: get line number and other information from Python call stack

Time:2021-8-5

Log printing or message uploading in the program, such as Kafka message, etc. Among the frequently uploaded messages, the file name, line number, upper layer caller and other specific positioning messages in the stack information need to be uploaded. Python provides the following two methods:

  • sys._getframe, basic method
  • inspect.currentframeIn addition to the recommended method, providesys._getframeMethod, there are more frame related methods

The specific use is as follows

usesys._getframePrivate method

The specific application methods are as follows:

import os
import sys


def get_cur_info():
	"""
        Get the file name, line number and the name of the upper caller when calling
        : Return: file name, line number, upper caller name
    """
	try:
		current_frame = sys._getframe(2)
		return os.path.basename(current_frame.f_code.co_filename), current_frame.f_lineno, current_frame.f_code.co_name
	except ValueError:
		return 'unknown', 0, 'unknown'

See the inspection module results below for specific function output results

useinspectModule (recommended)

Compared with the built-in private method of sys, the inspect module is recommended. The specific usage of the inspect module is as follows

import os
import inspect

def get_cur_info():
	try:
		current_frame = inspect.currentframe(2)
		return os.path.basename(current_frame.f_code.co_filename), current_frame.f_lineno, current_frame.f_code.co_name
	except ValueError:
		return 'unknown', 0, 'unknown'


def produce():
	return get_cur_info()


def business():
	return produce()


if __name__ == '__main__':
	print(get_ cur_ Info()) # output ('unknown ', 0,' unknown ')

	Print (produce()) # output ('a.py ', 22,' ')

	Print (business()) # output ('a.py ', 16,' business')

It mainly depends on the inspect.currentframe method. See the help document for the use of the inspect.currentframe method

>>> help(inspect.currentframe)
Help on built-in function _getframe in module sys:

_getframe(...)
    _getframe([depth]) -> frameobject
    
    Return a frame object from the call stack.  If optional integer depth is
    given, return the frame object that many calls below the top of the stack.
    If that is deeper than the call stack, ValueError is raised.  The default
    for depth is zero, returning the frame at the top of the call stack.
    
    This function should be used for internal and specialized
    purposes only.

Returns a frame object from the call stack. The depth is an integer, the default is 0, and the frame at the top of the call stack is returned. If the specified depth is deeper than the call stack, a valueerror exception is thrown. This function should only be used for internal and professional purposes.

See the built-in library inspect.py for the implementation of the inspect.currentframe method

if hasattr(sys, '_getframe'):
    currentframe = sys._getframe
else:
    currentframe = lambda _=None: None

Therefore, the inspect. Currentframe method is essentially equivalent to sys_ Getframe method

currentframe = lambda _= None: none is equivalent to currentframe = lambda: None, that is, the lambda function receives a parameter and returns none


reference resources:

  1. Python frame hack

  2. StackOverFlow-In Python, how do I obtain the current frame?


Remember to give me some praise!

Carefully sorted out the video courses and e-books in all directions of the computer, including introduction, advanced and actual combat. According to the reasonable classification according to the directory, you can always find the learning materials you need. What are you waiting for? Pay attention to the download!!!

resource-introduce

Never forget, there must be an echo. My friends, please give me a praise. Thank you very much.

I am a bright brother in the workplace, YY Senior Software Engineer, four years of working experience, and a slash programmer who refuses to be a leader.

Listen to me, more progress, program life is a shuttle

If you are lucky enough to help you, please give me a [like] and give me attention. If you can comment and encourage me, I will be very grateful.

Workplace bright brother article list:More articles

wechat-platform-guide-attention

All my articles and answers are in cooperation with the copyright protection platform. The copyright belongs to brother Liang in the workplace. Unauthorized reproduction must be investigated!