【问题标题】:python function that logs time & error when a script failed脚本失败时记录时间和错误的python函数
【发布时间】:2021-06-03 00:52:18
【问题描述】:

我正在使用 python3。我想在一行中打印脚本失败的时间,以及相应的异常。参考this link & this one,我尝试了类似的方法,但该函数没有执行。我在这里做错了吗?非常感谢您的建议。


import atexit
import datetime

#define function to log when script ends due to error/failure
def f_log(date_and_time, error):
    try:
        print("")
    except:
        print('Script ended at date/time: %s with error %s.' % (date_and_time, error))

import atexit
atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)

print "Deliberate error" # Simple example of an error that should be caught & printed along with time when script fails.

# main body of script continues here
#
#

【问题讨论】:

    标签: python exception logging error-handling


    【解决方案1】:

    您的脚本有多个问题。 (日期时间未导入,无用的尝试/f_log 中的除外,...)主要问题是无法处理 SyntaxError。试试这个版本:

    import atexit
    import datetime
    
    #define function to log when script ends due to error/failure
    def f_log(date_and_time, error):
        print('Script ended at date/time: %s with error %s.' % (date_and_time, error))
    
    
    atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)
    
    1/0 # Simple example of an error that should be caught & printed along with time when script fails.
    

    【讨论】:

    • 谢谢!我不知道不能以这种方式处理 SyntaxError;您使用的错误示例似乎没有问题。我想我将不得不更深入地研究哪些异常是异常。另一方面,我没有在代码 sn-p 中明确包含“导入”行,因为它与我遇到的问题无关;但在看到您的评论后,为了清楚起见,我编辑了我的帖子,因此其他人不会同样认为这可能是潜在的错误来源。
    猜你喜欢
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    相关资源
    最近更新 更多