0

I have a large Python app with a lot of functions. Sometimes a certain function reports an error to the log. I want to add a line number also, in order to find out the line in my code that failed.

Example of a function:

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)
SteveS
  • 3,789
  • 5
  • 30
  • 64
  • 1
    Does [this](https://stackoverflow.com/questions/1278705/when-i-catch-an-exception-how-do-i-get-the-type-file-and-line-number) answer your question? – Cory Kramer Apr 07 '20 at 19:34
  • Are you using the `logging` stdlib module? It's not clear what kind of logger `APP_LOG` is. The stdlib module provides the line number on the logrecord – blues Apr 07 '20 at 21:04

1 Answers1

1

Already answered: How to log source file name and line number in Python

Sure, check formatters in logging docs. Specifically the lineno and pathname variables.

%(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).

Looks something like this:

formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} 
Rajat Jain
  • 1,339
  • 2
  • 16
  • 29