Python日志logging(函数名称,文件名,行号)使用单个文件

我正试图学习一个应用程序如何工作。 为此,我将debugging命令作为每个函数的主体的第一行插入,目标是logging函数的名称以及将消息发送到日志输出的行号(代码内)。 最后,由于这个应用程序包含很多文件,我想创build一个日志文件,这样我就可以更好地理解应用程序的控制stream。

这是我所知道的:

  1. 为了获得函数名,我可以使用function_name.__name__但我不想使用function_name(这样我就可以在所有函数的主体中快速复制和粘贴一个通用的Log.info("Message") )。 我知道这可以使用__func__macros在C中完成,但我不知道有关Python。

  2. 为了得到文件名和行号,我已经看到(我相信)我的应用程序正在使用Python locals()函数,但在一个语法,我不完全知道例如: options = "LOG.debug('%(flag)s : %(flag_get)s' % locals()) ,我尝试使用类似LOG.info("My message %s" % locals())产生的东西像{'self': <__main__.Class_name object at 0x22f8cd0>} 。这个任何input请?

  3. 我知道如何使用日志logging,并添加处理程序来login到一个文件,但我不知道是否可以使用单个文件logging在项目中的函数调用的正确顺序的所有日志消息。

我将不胜感激任何帮助。

谢谢!

这里有一些与边缘相关的问题。

我将从最简单的开始:(3)。 使用logging可以将所有调用聚合到单个日志文件或其他输出目标:它们将按照它们在过程中发生的顺序。

接下来:(2)。 locals()提供当前范围的字典。 因此,在一个没有其他参数的方法中,你有self的范围,它包含对当前实例的引用。 正在使用的技巧是使用字典作为%运算符的RHS的string格式。 "%(foo)s" % bar将被bar["foo"]的值replace。

最后,您可以使用一些自省技巧,类似于可以logging更多信息的pdb使用的技巧:

 def autolog(message): "Automatically log the current function details." import inspect, logging # Get the previous frame in the stack, otherwise it would # be this function!!! func = inspect.currentframe().f_back.f_code # Dump the message + the name of this function to the log. logging.debug("%s: %s in %s:%i" % ( message, func.co_name, func.co_filename, func.co_firstlineno )) 

这将logging传入的消息,以及(原始)函数名称,定义出现的文件名以及该文件中的行。 看看检查 – 检查活物体的更多细节。

正如我在前面的评论中提到的那样,您可以随时通过插入行import pdb; pdb.set_trace()进入pdb交互式debugging提示符import pdb; pdb.set_trace() import pdb; pdb.set_trace() ,并重新运行你的程序。 这使您能够浏览代码,根据您的select检查数据。

正确的答案是使用已经提供的funcNamevariables

 import logging logger = logging.getLogger('root') FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s" logging.basicConfig(format=FORMAT) logger.setLevel(logging.DEBUG) 

然后,只要添加:

 logger.debug('your message') 

从我正在处理的脚本输出示例:

 [invRegex.py:150 - handleRange() ] ['[AZ]'] [invRegex.py:155 - handleRepetition() ] [[<__main__.CharacterRangeEmitter object at 0x10ba03050>, '{', '1', '}']] [invRegex.py:197 - handleMacro() ] ['\\d'] [invRegex.py:155 - handleRepetition() ] [[<__main__.CharacterRangeEmitter object at 0x10ba03950>, '{', '1', '}']] [invRegex.py:210 - handleSequence() ] [[<__main__.GroupEmitter object at 0x10b9fedd0>, <__main__.GroupEmitter object at 0x10ba03ad0>]]