Python日志错误是指函数中的错误行

时间:2019-03-20 19:05:08

标签: python-3.x logging error-logging

这里的新手将不胜感激。

下面是定义和调用函数的示例代码。我故意在第7行的代码中放置了一个错误,以查看程序遇到错误时日志记录的行为。

def addition(a,b):

    logging.getLogger(__name__).info("LOG")
    start = time.time()

    try:
        print("the first number is \n" + str(a))
        print("and the second one is \n" + str(b))
        prin(a+b)

    except Exception as e:
        logging.getLogger("LOG").error('this is an error,'+ str(e))


    end = time.time()
    logging.getLogger("LOG").log(20,'Function 1 Completed, time_finished: '
                                     + str(end - start)
                                     + ' seconds, '
                                     + str(50))

addition(2,3)

我得到的输出是:

the first number is

2

and the second one is 

3

2019-03-20 18:57:31,826 MAIN_LOGGER ERROR 0024 this is an error,name 'prin' is not defined

从本质上讲,我希望日志错误消息显示发生错误的实际行,而不是在我调用日志函数时显示。

请帮助:)

2 个答案:

答案 0 :(得分:1)

在打印回溯到日志以获取完整回溯时,请使用exception,而不是error

except Exception as e:
    logging.getLogger("MAIN_LOGGER").exception('Could not perform translation')

答案 1 :(得分:0)

您可以使用以下代码显示发生错误的行:

print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)

使用您的示例,就像这样:

import sys

def addition(a,b):
    try:
        print("the first number is \n" + str(a))
        print("and the second one is \n" + str(b))
        prin(a+b)

    except Exception as e:
        print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)