如何获取发生错误的行号而不是 Django 中记录错误的行号

How to get the line number where error occurred instead of line number from where error logged in Django

我在我的 Django 项目中使用日志记录来记录错误。但是,只要任何行发生任何错误,日志中的行号就是记录错误的位置,而不是发生错误的位置。
例如,在下面的代码中,如果错误发生在第 3 行(获取数据行 1 的代码),那么在日志中,发生日志记录的行号将打印为 7。

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 {}

下面是日志设置文件中格式化的代码。

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

错误消息示例:

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',)

如何获取发生错误的行号而不是记录错误的行号。

查找 python 中的行号需要 bit of work。如果您真的有兴趣添加行号,您可以这样做:

from inspect import currentframe

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

但它并没有真正添加任何重要的内容。当出现问题时,您真正需要的是堆栈跟踪。这最好用

来实现
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 {}