【问题标题】:Exception message best practices [closed]异常消息最佳实践 [关闭]
【发布时间】:2016-09-27 12:39:38
【问题描述】:

我用 Python 编写了一个带有标准异常处理的小型生产级 Flask 应用程序。大多数时候我只是记录异常消息,它看起来像这样

try:
    #Do something
except Exception, e:
    logger.error('Exception in LoadValidationDocs in main.py : %s' % str(e.args))
    return None

我想知道是否应该将所有此类错误消息保存在单独的 strings.py 文件中,例如

standard_exception_message = 'Exception in %s in %s, Exception Args : %s'

并在运行时获取函数和模块名称,如

import inspect
function_name = inspect.stack()[0][3]
file_name = os.path.basename(__file__)
logger.error(strings. standard_exception_message % (function_name, file_name, str(e.args)))

我只是想知道是否有必要这样做,考虑到我目前的情况,这是否是正确的做法。

【问题讨论】:

  • 你应该使用except Exception as e: 而不是except Exception, e: related answer

标签: python string exception


【解决方案1】:

您可以使用logging.exception 代替logging.error。它会以格式化的方式为您查找函数、模块名称等:

import logging

try:
    # Do something that will fail
    x = 1 / 0
except Exception as e:
    logger.exception("This is my message when an error happens here.")

它给出:

ERROR:root:This is my message when an error happens here.
Traceback (most recent call last):
  File "question39724934.py", line 5, in compute
    x = 1 / 0
ZeroDivisionError: division by zero

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2010-09-07
    • 2023-04-10
    • 1970-01-01
    • 2013-01-13
    相关资源
    最近更新 更多