Skip to content

Instantly share code, notes, and snippets.

@logikal
Last active August 2, 2017 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logikal/4cf0d960209f600c0b1b9d7ae28c941e to your computer and use it in GitHub Desktop.
Save logikal/4cf0d960209f600c0b1b9d7ae28c941e to your computer and use it in GitHub Desktop.
using traps to send graphite metrics in bash scripts
#!/usr/bin/env bash
starttime=$(date +%s)
########
# Set up a set of functions and traps that will emit duration and error counts for this script on exit.
# expects that $GRAPHITE_HOST is set in the environment.
function emit_duration {
endtime=$(date +%s)
duration=$(($endtime-$starttime))
echo "foo.duration $duration `date +%s`" | nc -w 1 $GRAPHITE_HOST 2003
}
function emit_error {
# we have to trap exit here so that we don't hit both emit_error and emit_success
trap - EXIT
echo "foo.error 1 `date +%s`" | nc -w 1 $GRAPHITE_HOST 2003
}
function emit_success {
echo "foo.success 1 `date +%s`" | nc -w 1 $GRAPHITE_HOST 2003
}
function success_trap {
emit_duration; emit_success;
}
function error_trap {
emit_duration; emit_error;
}
# a reasonable set of things to call an error
trap error_trap HUP INT QUIT PIPE TERM
# the success case
trap success_trap 0
########
# do some things
sleep 10;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment