Report errors from Zappa scheduled functions


#1

I’m using Zappa to deploy my Python Flask app on AWS Lambda. Zappa allows a function to be scheduled to run at certain intervals, which I’m using to send emails about trial expiration.

I just discovered that errors that happen in the scheduled functions are not reported by Sentry. I only discovered the errors in the Cloudwatch logs.

Is there something I can config to enable Sentry when running scheduled functions with Zappa?

This is how I configured my flask app and scheduled functions:

common.py

from flask import Flask
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration 

app = Flask(__name__)

if app.debug:
  sentry_sdk.init(
    transport=print
  )
else:
  sentry_sdk.init(
    dsn="...", # Actual DNS here
    integrations=[FlaskIntegration(), AwsLambdaIntegration()]
  )

scheduled.py

from common import app

def sendTrialExpiredEmail():
  with app.app_context():
    ... # Code to send emails here, which had an error that wasn't reported by Sentry

zappa_settings.py

{
  "production": {
    "app_function": "main.app",
    "events": [{
        "function": "scheduled.sendTrialExpiredEmail",
        "expression": "rate(1 hour)"
    }]
    # Other irrelevant configs
  }
}

#2

I was able to work around this by catching the exceptions and reporting them using Sentry manually. I created a helper context to do this. Here is my updated code that works:

common.py

from flask import Flask
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration 
from contextlib import contextmanager
import sentry_sdk

app = Flask(__name__)

if app.debug:
  sentry_sdk.init(
    transport=print
  )
else:
  sentry_sdk.init(
    dsn="...", # Actual DNS here
    integrations=[FlaskIntegration(), AwsLambdaIntegration()]
  )

@contextmanager
def scheduledContext():
  with app.app_context():
    try:
      yield
    except Exception as e:
      print("Uncaught exception", e)
      sentry_sdk.capture_exception(e)

scheduled.py

import common

def sendTrialExpiredEmail():
  with common.scheduledContext():
    # Code to send emails here. 
    # Exceptions and logging.error messages go to Sentry
    ...

zappa_settings.py

{
  "production": {
    "app_function": "main.app",
    "events": [{
        "function": "scheduled.sendTrialExpiredEmail",
        "expression": "rate(1 hour)"
    }]
    # Other irrelevant configs
  }
}

#3

Hi, this sounds like a bug. I am not sure if we will be able to fix this anytime soon but please do file a bug report against https://getsentry.github.io/sentry-python/ anyway