SteveS
SteveS

Reputation: 4040

Add code line when printing the log in Python 3?

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)

Upvotes: 0

Views: 531

Answers (1)

audiomagicus
audiomagicus

Reputation: 26

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} 

Upvotes: 1

Related Questions