在 AWS Lambda 上使用 Flask 的哨兵无法捕获错误

Sentry with Flask on AWS Lambda not capturing errors

我已经在 AWS lambda 上部署了一个 Flask 应用程序。为了执行错误跟踪,我想将 Sentry 集成到应用程序中。这是我的应用程序设置

def _handle_error(e):
    code = 500
    msg = 'Not Found'

    if isinstance(e, HTTPException):
        code = 404
    elif isinstance(e, ValueError):
        msg = str(e)

    logging.exception(e)

    if os.getenv('SENTRY_DSN'):
        event_id = sentry_sdk.capture_exception(e)
        logging.info(f'Error event was sent to sentry, event id: {event_id}')

    return jsonify({'error': msg}), code


def create_app():
    app = Flask(__name__)
    CORS(app, support_credentials=True)

    if os.getenv('SENTRY_DSN'):
        sentry_logging = LoggingIntegration(
            level=logging.DEBUG,     # Capture info and above as breadcrumbs
            event_level=logging.ERROR  # Send errors as events
        )

        sentry_sdk.init(dsn=os.getenv('SENTRY_DSN'),
                        integrations=[FlaskIntegration(), sentry_logging])

    app.register_blueprint(bp_routes)

    app.register_error_handler(Exception, _handle_error)

我使用 flask 中的自定义错误处理程序来 return 没有任何敏感信息的一般错误消息。捕获错误时,我试图在 Sentry

中手动创建一个事件
event_id = sentry_sdk.capture_exception(e)

运行 本地代码 python application.py 一切正常,事件在 Sentry 中创建并具有预期值。

将相同的代码部署到 lambda 时,不再生成事件。

还有当我删除自定义烧瓶错误处理程序时

# app.register_error_handler(Exception, _handle_error)

并将其部署到生成事件的 lambda!

为什么 capture_exception 在 lambda 上不工作?

在 AWS Lambda 下使用任何 Web 框架另外 需要安装 AWS Lambda integration

对于类似于 AWS Lambda 的服务,generic serverless integration 可能会有用。