本文主要是介绍python log 打印函数名和调用关系,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
python log打印
关于log打印,如果需要自定义输出到文件,当然是logging库
但是logging不能打印出每个调用函数的调用关系,在看log去找问题的时候有时候会很头疼
这样需要打印每一步的执行流程可以参考使用inspect模块
小例子
写个测试代码,可以打印调用关系,先记录在这里:
myLog.py文件如下:
from inspect import getargvalues, stack
from re import findall
from time import strftime, localtime
import loggingERROR = "Error"
WARNING = "Warning"
INFO = "Info"
DEBUG = "Debug"
NOTSET = 0def get_class_from_frame(fr):args, _, _, value_dict = getargvalues(fr)if len(args) and args[0] == 'self':instance = value_dict.get('self', None)if instance:return getattr(instance, '__class__', None)return Noneclass MyLog(object):def __init__(self, log_file_path='test'):self.filename = log_file_path + ".log"logging.basicConfig(filename=self.filename, level=logging.DEBUG, filemode='a+', format='%(asctime)s [%(chain)s] %(message)s')def get_meta_data(self):frames = stack()chain_list = []for i in range(0, len(frames)):_, file_path, _, func_name, _, _ = frames[i]file_name = file_path.split('/')[-1]try:args = findall('\((.*)\)', frames[i+1][-2][0])[0]except IndexError as e:func_name = get_class_from_frame(frames[0][0]).__name__args = ''current_chain = '%s:%s(%s)' % (file_name, func_name, args)chain_list.append(current_chain)return list(reversed(chain_list))def write(self, message=" ", level=NOTSET):if level == NOTSET: # 默认显示所有调用目录info= ' --> '.join(self.get_meta_data()[:-2])else:info= levellogging.info(message, extra={'info': info})
test.py
import myLog as Log
log = Log.MyLog("text")
class Test1:def test1(self):log.write( f"Read file fail", Log.ERROR) # 不显示执行过程,显示错误等级def test2(self):log.write(f"Show some thing ... ") # 显示执行过程t = Test1()
t.test1()
t.test2()
生成log如下:
2020-04-23 16:29:07,200 [Error] Read file fail
2020-04-23 16:29:07,234 [test.py:MyLog() --> test.py:test2()] Show some thing ...
这篇关于python log 打印函数名和调用关系的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!