【问题标题】:Add code line when printing the log in Python 3?在 Python 3 中打印日志时添加代码行?
【发布时间】:2020-04-07 19:32:21
【问题描述】:

我有一个包含很多功能的大型 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)

【问题讨论】:

  • this 回答你的问题了吗?
  • 您在使用logging stdlib 模块吗?目前尚不清楚APP_LOG 是哪种记录器。 stdlib 模块在日志记录中提供行号

标签: python python-3.x logging


【解决方案1】:

已经回答: How to log source file name and line number in Python

当然,请检查日志文档中的格式化程序。特别是 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} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2019-10-15
    • 2011-06-05
    • 2013-12-21
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多