gpt4 book ai didi

python - 如何使用 Python 记录当前行和堆栈信息?

转载 作者:IT老高 更新时间:2023-10-28 20:49:42 30 4
gpt4 key购买 nike

我有如下的日志记录功能。

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com