我有如下的日志记录功能。
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']
最佳答案
当前函数名称、模块和行号,您只需更改格式字符串以包含它们即可。
logging.basicConfig(
filename = fileName,
format = "%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s",
level = logging.DEBUG
)
大多数人在记录异常时只需要堆栈,如果您调用 logging.exception()
,记录模块会自动执行此操作。如果您确实需要其他时间的堆栈信息,那么您将需要使用 traceback 模块来提取您需要的其他信息。
关于python - 如何使用 Python 记录当前行和堆栈信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5093075/