如何使用 Python 记录当前行和堆栈信息?
我有如下记录功能。
logging.basicConfig(
filename = fileName,
format = "%(levelname) -10s %(asctime)s %(message)s",
level = logging.DEBUG
)
def printinfo(string):
if DEBUG:
logging.info(string)
def printerror(string):
if DEBUG:
logging.error(string)
print string
我需要登录行号,堆栈信息。例如:
1: def hello():
2: goodbye()
3:
4: def goodbye():
5: printinfo()
---> Line 5: goodbye()/hello()
我怎样才能用Python做到这一点?
已解决为
def printinfo(string):
if DEBUG:
frame = inspect.currentframe()
stack_trace = traceback.format_stack(frame)
logging.debug(stack_trace[:-1])
if LOG:
logging.info(string)
我提供了这些信息,这正是我所需要的。
DEBUG 2011-02-23 10:09:13,500 [
' File "/abc.py", line 553, in <module>\n runUnitTest(COVERAGE, PROFILE)\n',
' File "/abc.py", line 411, in runUnitTest\n printinfo(string)\n']
I have logging function as follows.
logging.basicConfig(
filename = fileName,
format = "%(levelname) -10s %(asctime)s %(message)s",
level = logging.DEBUG
)
def printinfo(string):
if DEBUG:
logging.info(string)
def printerror(string):
if DEBUG:
logging.error(string)
print string
I need to login the line number, stack information. For example:
1: def hello():
2: goodbye()
3:
4: def goodbye():
5: printinfo()
---> Line 5: goodbye()/hello()
How can I do this with Python?
SOLVED
def printinfo(string):
if DEBUG:
frame = inspect.currentframe()
stack_trace = traceback.format_stack(frame)
logging.debug(stack_trace[:-1])
if LOG:
logging.info(string)
gives me this info which is exactly what I need.
DEBUG 2011-02-23 10:09:13,500 [
' File "/abc.py", line 553, in <module>\n runUnitTest(COVERAGE, PROFILE)\n',
' File "/abc.py", line 411, in runUnitTest\n printinfo(string)\n']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您只需更改格式字符串以包含当前函数名称、模块和行号即可。
大多数人只在记录异常时才需要堆栈,并且如果您调用
logging.exception()
,日志记录模块会自动执行此操作。如果您确实需要其他时间的堆栈信息,那么您将需要使用回溯模块来提取您需要的附加信息。Current function name, module and line number you can do simply by changing your format string to include them.
Most people only want the stack when logging an exception, and the logging module does that automatically if you call
logging.exception()
. If you really want stack information at other times then you will need to use the traceback module for extract the additional information you need.使用 stack_trace[:-1] 避免在堆栈跟踪中包含 method/printinfo。
Use stack_trace[:-1] to avoid including method/printinfo in the stack trace.
从 Python 3.2 开始,这可以简化为将
stack_info=True
标志传递给 记录调用。但是,您需要对任何早期版本使用上述答案之一。As of Python 3.2, this can be simplified to passing the
stack_info=True
flag to the logging calls. However, you'll need to use one of the above answers for any earlier version.迟到的回答,但是哦,好吧。
另一个解决方案是,您可以使用文档中指定的过滤器创建自己的格式化程序 此处。这是一个非常棒的功能,因为您现在不再需要使用辅助函数(并且必须将辅助函数放在您想要堆栈跟踪的任何地方)。相反,自定义格式将其直接实现到日志本身中。
注意:在上面的代码中,我修剪了最后 5 个堆栈帧。这只是为了方便,这样我们就不会显示 python 日志记录包本身的堆栈帧。(它也可能需要针对不同版本的日志记录包进行调整)
Late answer, but oh well.
Another solution is that you can create your own formatter with a filter as specified in the docs here. This is a really great feature as you now no longer have to use a helper function (and have to put the helper function everywhere you want the stack trace). Instead, a custom formatted implements it directly into the logs themselves.
Note: In the above code I trim the last 5 stack frames. This is just for convenience and so that we don't show stack frames from the python logging package itself.(It also might have to be adjusted for different versions of the logging package)
使用 traceback 模块。
Use the traceback module.
这是一个例子,我希望它可以帮助你:
结果:
Here is an example that i hope it can help you:
Result:
查看回溯模块
Look at traceback module
这是基于@mouad的答案,但通过在每个级别包含文件名(但不是其完整路径)和调用堆栈的行号,并将堆栈保留在最近调用的位置(IMO),变得更有用(IMO)即不颠倒)顺序,因为这就是我想要阅读它的方式:-)
每个条目都有 file:line:func() ,它与正常的堆栈跟踪序列相同,但都在同一行上,因此更加紧凑。
如果您有任何中间调用来生成日志文本,您可能需要添加额外的 f_back。
产生如下输出:
我只需要在两个关键函数中使用此堆栈跟踪,因此我将调用者的输出添加到 logger.debug() 调用中的文本中,如 htis:
This is based on @mouad's answer but made more useful (IMO) by including at each level the filename (but not its full path) and line number of the call stack, and by leaving the stack in most-recently-called-from (i.e. NOT reversed) order because that's the way I want to read it :-)
Each entry has file:line:func() which is the same sequence as the normal stacktrace, but all on the same line so much more compact.
You may need to add an extra f_back if you have any intervening calls to produce the log text.
Produces output like this:
I only need this stacktrace in two key functions, so I add the output of callers into the text in the logger.debug() call, like htis: