使用日志量而不是%asctime标记python记录器文件

时间:2018-01-25 17:55:43

标签: python linux python-2.7 logging embedded

我在Python 2.7代码中使用记录器来创建用于绘制的CSV。 它在没有RTC的嵌入式模块上运行。 我对时间戳没有任何用处,但是想要包含一个标签,所以我可以更容易地绘制它们。记录器的设置方式使其在重新启动之间继续。

我目前正在使用格式化程序来提供如下标签:

# Add formatter to the file handler.
formatter = logging.Formatter('%(asctime)s,%(message)s','%H:%M:%S')
fh.setFormatter(formatter)

但由于董事会没有RTC,只想将行号记录为标签而不是时间。

如何解决这个问题?我不能只有一个增量整数,因为下次程序启动它将从头开始而不是增量。

提前致谢!

1 个答案:

答案 0 :(得分:0)

要在记录器输出中显示当前代码行,这可能是您的答案

import logging
from inspect import currentframe, getframeinfo


logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(line)s - %(message)s')

logger = logging.getLogger()

logger.debug('Hi', extra={'line': getframeinfo(currentframe()).lineno})

如果要显示已打开文件或CVS的行号,可以将 extra 字典中的值更改为适当的属性。

请不要忘记在所有调试语句中包含额外字典。

干杯! :)