2

I am using logging in my django project to log errors. However whenever any error occurs at any line, the line number in logs is where the error was logged and not where the error occured.
For example in below code if error occured at 3rd line (code to get data line 1) then in logs line number will be printed as 7 where logging happened.

def get_gender(): try: # code to get data line 1 # code to get data line 2 # return data dictionary except Exception as e: logging.getLogger("error_logger").error(repr(e)) return {} 

Below is the code of formatted in logging settings file.

formatters':{ 'large':{ 'format':'%(asctime)s %(levelname)s %(process)d %(pathname)s '+ '%(funcName)s %(lineno)d %(message)s ' }, 

Error message example:

2017-05-06 15:20:07,065 ERROR 7000 /home/USER/ASonline/common/services/category_services.py get_gender 7 IndexError('list index out of range',) 

How can I get the line number where error occurred instead of line number from where error logged.

1 Answer 1

1

Finding the line number in python takes a bit of work. If you are really interested in adding the line number you can do this:

from inspect import currentframe logging.getLogger("error_logger").error("{0}: {1}".format(currentfram().lineno , repr(e))) 

But it doesn't really add anything important. What you really need when something goes wrong is a stacktrace. And that's best achieved with

import traceback try: # code to get data line 1 # code to get data line 2 # return data dictionary except Exception as e: logging.getLogger("error_logger").error(traceback.format_exc()) return {} 
Sign up to request clarification or add additional context in comments.

1 Comment

It is a little simpler to just use logging.getLogger(__name__).exception('my error message'). You don't even need to pass in the exception variable. It grabs it from sys.exc_info() if you are in an except block.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.