如何在Python日志中打印源代码行
有没有什么比较简单的方法,可以让我们在Python的日志报告中自动加入源代码的行?比如说……
import logging
def main():
something_is_not_right = True
logging.basicConfig(level=logging.DEBUG,
format=('%(filename)s: '
'%(levelname)s: '
'%(funcName)s(): '
'%(lineno)d:\t'
'%(message)s')
)
if something_is_not_right == True:
logging.debug('some way to get previous line of source code here?')
这样输出的结果就会像这样。
example.py: DEBUG: main(): 14: if something_is_not_right == True:
2 个回答
5
因为我看到unutbu尝试过类似的东西,所以我写了这段代码(现在发帖已经太晚了):
import logging, sys
# From logging.py
def currentframe():
"""Return the frame object for the caller's stack frame."""
try:
raise Exception
except:
return sys.exc_traceback
f = open(__file__.rstrip('c'))
owncode = f.readlines()
f.close()
def main():
something_is_not_right = True
logging.basicConfig(level=logging.DEBUG,
format=('%(filename)s: '
'%(levelname)s: '
'%(funcName)s(): '
'%(lineno)d:\t'
'%(message)s')
)
if something_is_not_right == True:
prev = owncode[currentframe().tb_frame.f_back.f_lineno - 2]
logging.debug('previous line of source code here:\n%s' % prev)
if __name__ == '__main__':
main()
21
import inspect
import logging
import linecache
def main():
something_is_not_right = True
logging.basicConfig(level=logging.DEBUG,
format=('%(filename)s: '
'%(levelname)s: '
'%(funcName)s(): '
'%(lineno)d:\t'
'%(message)s')
)
if something_is_not_right:
logging.debug(linecache.getline(
__file__,
inspect.getlineno(inspect.currentframe())-1))
if __name__=='__main__':
main()
test.py: DEBUG: main(): 18: if something_is_not_right == True:
产生