SQLAlchemy for Python

Learn how to set up Sentry's SQLAlchemy integration and how to capture SQLAlchemy queries as breadcrumbs and spans.

You need:

  • A Sentry account and project
  • Your application up and running
  • SQLAlchemy 1.2+
  • Python 3.6+

Follow our quick start guide to set up Sentry in your Python application (make sure to enable tracing). Sentry's SQLAlchemy integration is enabled automatically if you have the sqlalchemy package installed.

To verify that Sentry captures your SQLAlchemy queries, add this code to your app, which will create a transaction called testing_sentry in the Traces section and will create a span for the SELECT statement:

Copied
from sqlalchemy import create_engine
from sqlalchemy.sql import text

def main():
    # same as in the Pythn quick start guide (https://docs.sentry.io/platforms/python)
    sentry_sdk.init(...)

    engine = create_engine(DATABASE_URL, echo=True)
    statement = text("SELECT 'Hello World'")

    with engine.connect() as conn:
        # or sentry_sdk.traces.start_span(name="testing_sentry", parent_span=None) in stream mode
        with sentry_sdk.start_transaction(name="testing_sentry"):
            result = conn.execute(statement)

main()

At this point, you should have integrated Sentry into your application and should already be sending data to your Sentry project.

Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are:

Are you having problems setting up the SDK or integration?
Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").