Skip to content

Instantly share code, notes, and snippets.

@StevenACoffman
Forked from nstielau/send_metric_to_statsd.sh
Last active November 18, 2022 17:57
Show Gist options
  • Save StevenACoffman/73fbe230bc9d0cc5731577d8d7a867ab to your computer and use it in GitHub Desktop.
Save StevenACoffman/73fbe230bc9d0cc5731577d8d7a867ab to your computer and use it in GitHub Desktop.
Send a metric to StatsD from bash
# Send a metric to statsd from bash
#
# Useful for:
# deploy scripts (http://codeascraft.etsy.com/2010/12/08/track-every-release/)
# init scripts
# sending metrics via crontab one-liners
# sprinkling in existing bash scripts.
#
# netcat options:
# -w timeout If a connection and stdin are idle for more than timeout seconds, then the connection is silently closed.
# -u Use UDP instead of the default option of TCP.
#
echo "deploys.test.myservice:1|c" | nc -w 1 -u graphite.example.com 8125
# if netcat is hanging, try socat
#echo "deploys.test.myservice:1|c" | socat -t 0 STDIN UDP:graphite.example.com:8125

SENDING METRICS TO STATSD WITH A SHELL ONE-LINER

NOTE: From here

Etsy’s great post about tracking every release and has some good tips about tracking releases with statsd and graphite (including some essential graphite config tweaks). I was wondering how to do this from within a shell script, and I had to dig through lots of StatsD code and examples to find this snippet. I forget where I eventually found it, and thought it’d make it easier to find.

Deploy scripts are just one place where a concise and safe way to record a metric/event in important. From Etsy’s blog, using vertical lines to represent distinct events (code deployments) to give more context to the login trends:

Sending a metric from the command line, with netcat or curl, is just one bit of ‘glue’ that is essential for pulling together a complete metrics solution. This is essentially the base-case, the lowest-common-denominator that all metrics collection can be built upon.

While short-and-sweet, this snippit contains two measures of protection. First, it limits the run duration to a single second so it don’t have to worry about it hanging, and secondly, it uses UDP, so you don’t need to worry about the remote server being performant or even up. True fire-and-forget, so you can recklessly drop this in scripts left and right.

And the bash one-liner:

@xosofox
Copy link

xosofox commented Jan 16, 2020

If nc is not available, you can use:

echo "deploys.test.myservice:1|c" > /dev/udp/graphite.example.com/8125

@StevenACoffman
Copy link
Author

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment