Добавить строку кода при печати журнала в Python 3? - PullRequest
0 голосов
/ 07 апреля 2020

У меня есть большое приложение 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)

1 Ответ

1 голос
/ 08 апреля 2020

Уже ответили: Как записать имя исходного файла и номер строки в Python

Конечно, проверьте форматеры в документации журналов. В частности, переменные linen и 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} 
...