What you need
- A Linux or macOS machine whose jobs run from cron or a systemd timer, with
curl(nothing else: nojq, no Python). - An Ahem account (the free plan is enough), a project for your servers, and an API key for it.
- The Ahem app on your phone, or browser notifications turned on.
Set up a cron job failure notification, step by step
Create a project and a key. In Ahem, create a project, for example “Servers”, and an API key for it. Note the project’s address: addresses are unique across Ahem, so yours may be
servers-48213rather thanservers. The app shows it in the example request next to the key.Save the wrapper as
run-and-report.shand install it:#!/bin/sh # run-and-report: runs a command, and tells Ahem when it fails. # Usage: run-and-report NAME COMMAND [ARGUMENTS...] # AHEM_KEY an API key of your project # AHEM_PROJECT the project's address, as the app shows it # AHEM_CHANNEL the channel, "cron" if not set # AHEM_ON_SUCCESS set to 1 to also record successful runs (sent silent, so they never buzz) # The job's exit code is this script's exit code, and its output (standard error merged into # standard output) is printed when the job ends, so cron mail and log files still get it. [ $# -ge 2 ] || { echo "usage: run-and-report NAME COMMAND [ARGUMENTS...]" >&2; exit 64; } name=$1; shift log=$(mktemp) || exec "$@" # no temporary file: run the job anyway, unreported trap 'rm -f "$log"' EXIT trap 'exit 143' TERM; trap 'exit 130' INT; trap 'exit 129' HUP # so the EXIT trap cleans up when killed start=$(date +%s) "$@" >"$log" 2>&1 code=$? duration=$(($(date +%s) - start)) cat "$log" [ "$code" -ne 0 ] || [ "${AHEM_ON_SUCCESS:-0}" = 1 ] || exit 0 if [ -z "$AHEM_PROJECT" ] || [ -z "$AHEM_KEY" ]; then echo "run-and-report: set AHEM_KEY and AHEM_PROJECT to report to Ahem" >&2; exit "$code" fi # A JSON string: control characters dropped (tabs kept), \ and " escaped, lines joined with \n. json() { # Invalid UTF-8 would make Ahem refuse the event, so iconv drops it. Without iconv, cat passes the text on. { iconv -c -f UTF-8 -t UTF-8 2>/dev/null || cat; } | tr -d '\000-\010\013-\037' | awk 'BEGIN { ORS = "" } { gsub(/\\/, "&&"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); if (NR > 1) print "\\n"; print }' } host=$(uname -n) if [ "$code" -eq 0 ]; then title="$name succeeded on $host"; level=success; type=cron.succeeded; notify=silent body="Took ${duration}s." else title="$name failed on $host (exit $code)"; level=error; type=cron.failed; notify=default body=$(printf 'Exit code %s after %ss. The last lines of output:\n\n~~~\n%s\n~~~' \ "$code" "$duration" "$(tail -n 20 "$log" | LC_ALL=C cut -c 1-400)") fi # The key goes in a file only you can read, not on curl's command line, where ps would show it. headers=$(mktemp) || exit "$code" trap 'rm -f "$log" "$headers"' EXIT printf 'Authorization: Bearer %s\n' "$AHEM_KEY" >"$headers" response=$(printf '{"title":"%s","body":"%s","level":"%s","type":"%s","notify":"%s","group":"%s", "metadata":{"job":"%s","host":"%s","exit_code":%s,"duration_s":%s}}' \ "$(printf '%s' "$title" | json)" "$(printf '%s' "$body" | json)" "$level" "$type" "$notify" \ "$(printf '%s' "$name" | json)" "$(printf '%s' "$name" | json)" "$(printf '%s' "$host" | json)" \ "$code" "$duration" | curl -sS -m 10 --retry 3 --retry-connrefused "https://api.useahem.com/v1/channels/$AHEM_PROJECT/${AHEM_CHANNEL:-cron}" \ -H @"$headers" -H "Content-Type: application/json" \ -H "Idempotency-Key: $host-$name-$start-$$" --data-binary @- -w '\n%{http_code}' 2>&1) case $(printf '%s' "$response" | tail -n 1) in 2??) ;; *) printf 'run-and-report: Ahem did not take the event: %s\n' "$response" >&2 ;; esac exit "$code"sudo install -m 755 run-and-report.sh /usr/local/bin/run-and-reportIt runs the job with its output (standard error included) going to a temporary file, then prints that output, so your log files and cron mail still get it. The key goes to
curlin a file, so it doesn’t show inps. The JSON is escaped withawkand invalid UTF-8 is dropped withiconv, so quotes, backslashes, colour codes or binary junk in the output can’t get the event refused. Each job name is the event’sgroup, so all runs of one job are one thread in the inbox. Every field it sends is in the API reference.Put it in front of the job in your crontab (
crontab -e), with the key and the address at the top. Cron doesn’t read your shell profile, so they have to be here. The log goes to your home folder: in a normal user’s crontab, a log file the user can’t write to (such as one in/var/log) stops the job from starting at all.AHEM_KEY=ak_live_… AHEM_PROJECT=servers-48213 # m h dom mon dow command 0 3 * * * /usr/local/bin/run-and-report nightly-backup /usr/local/bin/backup.sh >> "$HOME/backup.log" 2>&1Try a failure by hand. Your phone shows “test-job failed on … (exit 1)” and the wrapper exits 1, like the command:
AHEM_KEY=ak_live_… AHEM_PROJECT=servers-48213 \ run-and-report test-job sh -c 'echo "something broke" >&2; exit 1'
For example, a backup that couldn’t reach its database sends this event:
{
"title": "nightly-backup failed on web-1 (exit 1)",
"body": "Exit code 1 after 2s. The last lines of output:\n\n~~~\ndumping database shop\npg_dump: error: connection to server on socket \"/var/run/postgresql/.s.PGSQL.5432\" failed: No such file or directory\n~~~",
"level": "error",
"type": "cron.failed",
"notify": "default",
"group": "nightly-backup",
"metadata": { "job": "nightly-backup", "host": "web-1", "exit_code": 1, "duration_s": 2 }
}With a systemd timer
If the job is a systemd service started by a timer, let systemd report it. OnFailure= starts another unit when the service fails, and that also covers what a wrapper can’t see from inside: a TimeoutStartSec timeout, a crash or the out-of-memory killer. The result is in the title (exit-code, timeout, signal, oom-kill), and the last 20 lines come from this run’s journal only.
The job and its timer, with one extra line, OnFailure=:
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
OnFailure=ahem-failed@%n.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh# /etc/systemd/system/backup.timer
[Unit]
Description=Run the backup every night at 03:00
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.targetOne template unit that any service can name in its OnFailure=, and the key in a file only root can read:
# /etc/systemd/system/ahem-failed@.service
[Unit]
Description=Tell Ahem that %i failed
[Service]
Type=oneshot
EnvironmentFile=/etc/ahem.env
ExecStart=/usr/local/bin/ahem-failed %i# /etc/ahem.env (sudo chmod 600 /etc/ahem.env)
AHEM_KEY=ak_live_…
AHEM_PROJECT=servers-48213The script it runs, saved as ahem-failed.sh:
#!/bin/sh
# ahem-failed: tells Ahem that a systemd unit failed. Started by ahem-failed@.service, which
# systemd runs through OnFailure= with the failed unit's name as the argument.
unit=$1
show() { systemctl show -p "$1" --value "$unit"; }
result=$(show Result) # exit-code, timeout, signal, oom-kill, …
code=$(show ExecMainStatus)
lines=$(journalctl _SYSTEMD_INVOCATION_ID="$(show InvocationID)" -n 20 -o cat --no-pager | LC_ALL=C cut -c 1-400)
host=$(uname -n)
json() {
# Invalid UTF-8 would make Ahem refuse the event, so iconv drops it. Without iconv, cat passes the text on.
{ iconv -c -f UTF-8 -t UTF-8 2>/dev/null || cat; } | tr -d '\000-\010\013-\037' |
awk 'BEGIN { ORS = "" } { gsub(/\\/, "&&"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); if (NR > 1) print "\\n"; print }'
}
headers=$(mktemp) || exit 1 # the key goes in a file, not on curl's command line where ps shows it
trap 'rm -f "$headers"' EXIT
printf 'Authorization: Bearer %s\n' "$AHEM_KEY" >"$headers"
body=$(printf 'Result: %s, exit status %s. The last lines of its log:\n\n~~~\n%s\n~~~' "$result" "$code" "$lines")
printf '{"title":"%s","body":"%s","level":"error","type":"cron.failed","group":"%s",
"metadata":{"unit":"%s","host":"%s","result":"%s","exit_code":%s}}' \
"$(printf '%s failed on %s (%s)' "$unit" "$host" "$result" | json)" "$(printf '%s' "$body" | json)" \
"$(printf '%s' "$unit" | json)" "$(printf '%s' "$unit" | json)" "$(printf '%s' "$host" | json)" "$result" "${code:-0}" |
curl -sS -m 10 --retry 3 --retry-connrefused "https://api.useahem.com/v1/channels/$AHEM_PROJECT/${AHEM_CHANNEL:-cron}" \
-H @"$headers" -H "Content-Type: application/json" \
-H "Idempotency-Key: $host-$(show InvocationID)" --data-binary @-Then install and start it:
sudo install -m 755 ahem-failed.sh /usr/local/bin/ahem-failed
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
sudo systemctl start backup.service # run it once now, to see a failure arriveTo report another service, add OnFailure=ahem-failed@%n.service to its [Unit] section.
Make it quieter
- Only failures buzz. The wrapper sends nothing for a successful run unless you set
AHEM_ON_SUCCESS=1; then successes are recorded as silent events, kept but never pushed. A job every five minutes makes about 8,640 events a month that way, more than the free plan’s 3,000, so keep it for the jobs whose history you want. - A channel per kind of job. Set
AHEM_CHANNELto send a noisy job somewhere else, then set that channel’s notification rule in the app: every event, warnings and errors, errors only, or off. - Count failures. A counter of
cron.failedfor this week, on the project overview, tells you if a flaky job is getting worse.
What a wrapper can’t catch: jobs that never run
The wrapper reports a job that ran and failed. It says nothing when the job never starts: the server is off, the crontab was overwritten, cron isn’t running, or the timer was disabled. Catching silence takes a heartbeat check, also called a dead man’s switch: the job pings a URL every time it succeeds, and a service alerts you when the ping doesn’t come. Free plans as their pricing pages listed them on 2 December 2026:
- Healthchecks.io is open source (BSD licence, self-hostable), and its free plan monitors 20 jobs.
- Cronitor has a free plan with 5 monitors.
- Ahem silence alerts are planned Planned. Until they ship, I’d use one of the two above for “didn’t run” and Ahem for “failed, and here’s the output”.
Troubleshooting
- It works in a terminal but not from cron. Cron runs with a short
PATH(often/usr/bin:/bin) and without your shell profile. Use full paths, and setAHEM_KEYandAHEM_PROJECTin the crontab as above. - A
%in the crontab line cuts the command short. Cron turns%into a new line. Write\%, for exampledate +\%F, or move the command into a script. - The job fails but no event arrives. Look at the job’s log: when Ahem refuses an event the wrapper prints
run-and-report: Ahem did not take the event:and the reason, such as a404for a wrong project address or a401for a wrong key. - The job fails but exits 0. A shell script exits with its last command’s code, so an error halfway through goes unnoticed. Start the script with
set -e; in bash, addset -o pipefailso a failure inside a pipe counts too. - The job hangs and nothing arrives. The wrapper waits for the job as long as it runs. Give it a limit with
timeout: when the limit is reached the job is stopped and the exit code is 124.0 3 * * * /usr/local/bin/run-and-report nightly-backup timeout 2h /usr/local/bin/backup.sh >> "$HOME/backup.log" 2>&1 - systemd: nothing arrives.
journalctl -u 'ahem-failed@*'shows the script’s run and Ahem’s answer. Check that/etc/ahem.envexists, and runsystemctl daemon-reloadafter editing a unit.
Other ways to do it
MAILTOin the crontab. Free and built in: cron emails whatever a job prints. It needs a working mail setup on the server, and it mails every job that prints anything, not only failures.chronicfrom moreutils helps there: it prints a job’s output only when the job fails.- A heartbeat service (above). It covers jobs that never run, which a wrapper can’t.
- A push service with the same wrapper. Point the
curlat ntfy or Pushover. You get the ping; you don’t get one searchable history of every failure across servers. See Ahem vs Pushover. - A Telegram bot. Works, with one chat for everything. See Ahem vs a Telegram bot.
What Ahem adds is the record: every failure from every server in one inbox, a thread per job, the output kept with it, and a rule per channel for what wakes you. The same API works from any other script.