首页 > 解决方案 > 在 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)

标签: pythonpython-3.xlogging

解决方案


已回答: 如何在 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} 

推荐阅读