Sending Sentry Events from Bash
One tool that you may already be familiar with is our handy sentry-cli command line client. Many Sentry users find it to be a very useful companion to work with releases, debug information files, generate source maps, and much more. But among all these useful features is one feature that is not nearly as well known as the rest: sentry-cli can be used to send events to Sentry.
That this is not well known is not particularly surprising since until very recently the feature was poorly documented and not actually all that useful. However, with sentry-cli 1.24.0 we decided to remedy this, and newer versions can now not only send much more useful data, but are more fun to use and are particularly useful for automatic error reporting from bash scripts.
Here’s how it works.
The prerequisite for all of this is a working
sentry-cli installation. While you can
install it in many ways, one very convenient approach is the infamous curl to bash
$ curl -sL https://sentry.io/get-cli/ | bash
Additionally, you need to tell
sentry-cli about your DSN for events. There are
multiple ways to configure it. One of those ways is to export the
$ export SENTRY_DSN=<your-dsn-goes-here>
After this is done, you can send events with very little extra effort. The bare minimum for sending an
event is to provide both the
-m parameter and a message for the event:
$ sentry-cli send-event -m "Something happened"
And with that, you’ll now start seeing events in the sentry UI:
Event environment variables and a bunch of information about your machine will be sent along. That’s useful, but with a few extra steps we can make it even more so.
A quite common situation is that you’ll want to send some breadcrumbs along when you inform Sentry of a failure. For instance, if you have a logfile that contains some information about the failure then you can provide it and the last 100 lines will be attached to the event as breadcrumbs.
$ sentry-cli send-event -m "Unknown system error" --logfile /var/log/system.log
We will make breadcrumbs out of the logfile and also automatically parse timestamps for you:
That isn’t all. The best part is that you can quickly enable error handling for your bash scripts. Add one line at the start of your script:
#!/bin/bash export SENTRY_DSN=<your dsn here> eval "$(sentry-cli bash-hook)"
And it turns on
set -e (which you should always use)
and hooks the error handling. After a failure in a script you’ll see an event
with traceback and all the output as breadcrumbs:
There are some limitations in bash that you should be aware of (we are registering an
ERR trap) but other than that it should be easy to use in your scripts.