从python源代码中提取完整的日志语句
你们能分享一下我如何从python源代码中提取logger语句吗 例如,我有以下代码片段:从python源代码中提取完整的日志语句,python,logging,abstract-syntax-tree,Python,Logging,Abstract Syntax Tree,你们能分享一下我如何从python源代码中提取logger语句吗 例如,我有以下代码片段: import logger def some_function(some_list): #multi-line logger logger.info("Inside some function") for item in some_list: logger.debug("item is {}}.format(item) 输出
import logger
def some_function(some_list):
#multi-line logger
logger.info("Inside
some function")
for item in some_list:
logger.debug("item is {}}.format(item)
输出应为:
logger.info("Inside some function") #converted to single line
logger.debug("item is {}}.format(item)
我在python中使用了AST模块,它为我提供了包含logger变量的源代码行
#tree is a AST parse tree of python source file
for node in ast.walk(tree):
#previous = node.parent
try:
for child in ast.iter_child_nodes(node):
#print("The length of child nodes is {}".format(len(ast.iter_child_nodes(node))))
if child.id == "logger":
print("The start line no is {} and end line no is {}".format(child.lineno,child.end_lineno))
except AttributeError:
pass
下面是AST脚本的输出:
The start line no is 150 and end line no is 150
logger = logging.getLogger(__name__)
The start line no is 226 and end line no is 226
logger.info
The start line no is 232 and end line no is 232
logger.info
The start line no is 294 and end line no is 294
logger.info
The start line no is 300 and end line no is 300
logger.info
The start line no is 303 and end line no is 303
logger.info
正如您所见,我无法检索整个记录器源代码行,非常感谢您的帮助,谢谢 使这项工作变得容易:
import ast
import astor
class LogPrinter(astor.TreeWalk):
def pre_Call(self):
if (isinstance(self.cur_node.func, ast.Attribute) and
isinstance(self.cur_node.func.value, ast.Name) and
self.cur_node.func.value.id == "logger"
):
print(astor.to_source(self.cur_node), end="")
您可以用类似于LogPrinter(ast.parse(some\u source\u code))
的东西来调用它
它的工作原理是在ast树中查找任何ast.Call
节点,然后检查调用是否是在名为logger
的属性上进行的。如果需要,您可以在其他逻辑中进行替换,这只是一个适用于特定示例代码的快速且肮脏的版本(如果语法错误已修复):
输出为:
logger.info('Inside some function')
logger.debug('item is {}'.format(item))
当你尝试这样做时遇到了什么困难?你剪下的最后一行在语法上是不正确的。这是故意的吗(与您问题上的标记有关)?这只是一个例子,我无法借助ASTs提取相关信息,您知道如何从源代码中获取整个日志记录语句吗?@mkrieger1我已更新了问题。感谢您提供的代码片段,我学到了一些新的东西,我可以问另一个问题,但由于这有点相关,请在这里提问。我想带着astor进入节点,我读了这个链接:它有iter节点功能,我想在刚刚发现的logger节点上方获取源代码行
logger.info('Inside some function')
logger.debug('item is {}'.format(item))