Reporting Exceptions in Python Scripts with Sentry

Python scripts are the glue that keep many applications and their infrastructure running, but when one of your scripts throws an exception you may not know about it immediately unless you have a central place to aggregate the errors. That’s where adding Sentry can solved this distributed error logging problem.

In this tutorial, we’ll see how to quickly add Sentry to a new or existing Python script to report errors into a centralized location for further debugging.

  • Development environment setup

    Make sure you have Python 3 installed. As of right now, Python 3.8.3 is the latest version of Python.

    During this tutorial we’re also going to use:

    • a hosted Sentry instance on sentry.io, which we’ll need an account to access
    • the Sentry Python helper library to send exception data to our Sentry instance

    Install the above code libraries into a new Python virtual environment using the following commands:

    python -m venv sentryscript
    source sentryscript/bin/activate
    
    pip install sentry-sdk>=0.14.4
  • Our development environment is now ready and we can write some code that will throw exceptions to demonstrate how to use Sentry.
  • An Example Script for Loading Python Modules

    We’ll start by writing a small but useful script that prints out the names of all modules within a Python package, then add Sentry to it when it becomes apparent that capturing exceptions would be a useful addition.

    Create a new file named module_loader.py and write the following lines of code in it to allow us to easily execute it on the command line.

    import argparse
    
    def import_submodules(package):
        return {}
    
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument("package")
        args = parser.parse_args()
    
        package_to_load = args.package
        results = import_submodules(package_to_load)
        for r in results:
            print(str(r))
  • Adding Exception Reporting with Sentry

    Sentry can either be self-hosted or used as a cloud service through Sentry.io. In this tutorial we will use the cloud hosted version because it’s faster than setting up your own server as well as free for smaller projects.

Leave a Reply

Call Us