python - 在 Python 3 中打印日志时添加代码行?
问题描述
我有一个带有很多功能的大型 Python 应用程序。有时某个函数会向日志报告错误。我还想添加一个行号,以便找出我的代码中失败的行。
函数示例:
def count_user_reminders(userid):
""" Count amount of user's unmuted reminders in the system """
reminders_count = -7
try:
with pg_get_cursor(POOL) as cursor:
query = """ SELECT COUNT(*)
FROM reminders r, basketdrugs b
WHERE r.busketdrugsid = b.id
AND r.muted = False
AND b.usersid = %s; """
cursor.execute(query, (userid, ))
res = cursor.fetchone()
if res:
reminders_count = res[0]
except Exception as err:
APP_LOG.error(ERROR_TEMPLATE, err)
解决方案
当然,请检查日志记录文档中的格式化程序。特别是 lineno 和 pathname 变量。
%(pathname)s Full pathname of the source file where the logging call was issued(if available).
%(filename)s Filename portion of pathname.
%(module)s Module (name portion of filename).
%(funcName)s Name of function containing the logging call.
%(lineno)d Source line number where the logging call was issued (if available).
看起来像这样:
formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d}
推荐阅读
- java - 如何从内部匹配值中获取节点键
- c++ - 无限输入的正则表达式
- java - 将功能放在 Hashmap 上
- mdx - MSAS m2m 属性未按预期解析
- javascript - facebook按钮不调用onClick() - reactJS
- javascript - Vue2:如何获得平滑的鼠标移动?
- javascript - JavaScript - 原型函数中的访问类实例属性
- android - 当我在清单中更改主题时强制停止
- python - Colaboratory - 记住 Google Drive Auth (Python)
- python - 无法在我的虚拟环境中安装 Tensor Flow