Python - 添加动态调试记录器样式的行号和时间函数



以下函数报告"当前"行号(和时间),当运行时发生异常时,我想从其他函数中调用该行号。

可以理解的是,返回的行号总是与 getframeinfo 在 gTime() 函数本身中的位置有关,即它是静态的。

每当我需要 line.num/time 数据时,我只需要 gTime() 功能,而无需直接将(长)gTime 代码添加到主代码正文中需要的每个位置。我想某种命令序列别名是我真正想要的来替换我的 gTime() 函数中的代码 - 但找不到我的问题的任何解决方案。

标准的"记录器"模块在我的多线程应用程序中无法可靠地工作,因此我求助于手动滚动解决方案。

from inspect import currentframe, getframeinfo
from datetime import datetime
def gTime():
    position = "%s [%s] - " % (str(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')),getframeinfo(currentframe()).lineno)
    return position 
print gTime()

如果你不能使用logging,我建议尽可能多地使用它的内部结构,或者至少从中学习;见 http://hg.python.org/cpython/file/tip/Lib/logging/__init__.py。

特别是,logging.currentframe可用于获取封闭框架:

from inspect import getframeinfo
from logging import currentframe
from datetime import datetime
def callingFrame():
    return getframeinfo(currentframe())
def gTime():
    position = "%s [%s] - " % (str(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')), callingFrame().lineno)
    return position 
print gTime()

"标准的'记录器'模块在我的多线程应用程序中无法可靠地工作,所以我求助于手动解决方案。"

文档不同意

日志记录模块旨在实现线程安全,无需任何特殊 需要由客户完成的工作。它通过使用 螺纹锁;有一个锁可以序列化对模块的访问 共享数据,每个处理程序还创建一个锁来序列化访问 到其底层 I/O。

为什么它不能可靠地工作?

最新更新