Browse files

Merge allow-piping (#1) into master

Allow piping data directly to the script with '-'

i.e. if `some-command` generates data like:

    thingA 4325
    thingB 243

Then you can send that directly to graphite with

    some-command | ./pipe-to-graphite.sh -
  • Loading branch information...
2 parents b91a0b0 + aa2dbc8 commit 52baf70fa5b3c5aa4e1b2b9346a67c74632fc4b3 @danielbeardsley danielbeardsley committed Dec 20, 2012
Showing with 20 additions and 2 deletions.
  1. +6 −1 README.md
  2. +14 −1 pipe-to-graphite.sh
View
7 README.md
@@ -39,7 +39,12 @@ Your script (lets say `~/glork-stats.sh`) would look something like this:
To get that regularly reported to Graphite, run this command
- pipe-to-graphite.sh ~/glork-stats.sh >> /var/log/glork-stats.log
+ ./pipe-to-graphite.sh ~/glork-stats.sh >> /var/log/glork-stats.log
+
+Or to report it to graphite at any time, if you want to use cron or something.
+The '-' argument indicates input should be read form stdin
+
+ ~/glork-stats.sh | ./pipe-to-graphite.sh -
### Logging
Output from each run is prepended with a timestamp and echoed to stdout
View
15 pipe-to-graphite.sh
@@ -20,9 +20,20 @@ if [ -f graphite.conf ]; then
source graphite.conf
fi
+# '-' indicates we should read from stdin
+if [ "$1" = "-" ]; then
+ # Get a timestamp for sending to graphite
+ ts=`date +%s`
+
+ # Pipe the output through sed, using a regex to
+ # append a $ts timestamp to the end of each line,
+ # and then to the correct server and port using netcat
+ sed -e '/ [0-9]\+$/!d' -e "s/\$/ $ts/" |
+ nc -w 1 $GRAPHITE_SERVER $GRAPHITE_PORT
+
# Normal usage just passes the command as the only parameter
# This checks if we're on a recursive call.
-if [ "$1" != "report-to-graphite" ]; then
+elif [ "$1" != "report-to-graphite" ]; then
command="$1"
# No point in attempting to run an empty command
@@ -41,6 +52,8 @@ if [ "$1" != "report-to-graphite" ]; then
cat <<-EOF >&2
Usage:
$(basename $0) '/command/to/run' >> /var/log/some-stats.log
+ Or (for use from cron or other automated invocations):
+ /command/to/run | $(basename $0) -
/command/to/run must:
* echo 'name number' pairs separated by newlines

0 comments on commit 52baf70

Please sign in to comment.