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)
2
  • 1
    Does this answer your question? Commented Apr 7, 2020 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 Commented Apr 7, 2020 at 21:04

1 Answer 1

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} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.