Skip to content

Instantly share code, notes, and snippets.

@tjsingleton
Created May 12, 2011 15:23
Show Gist options
  • Save tjsingleton/968735 to your computer and use it in GitHub Desktop.
Save tjsingleton/968735 to your computer and use it in GitHub Desktop.
Middleware that logs heroku requests into redis.
require "csv"
class HerokuEnvLogger
PREFIX = "HerokuRequest"
TIME_STEP = 1.minute * 1000 # ms
EXPIRE_IN = 6.hours
KEYS = %w[HTTP_X_REQUEST_START
HTTP_X_HEROKU_QUEUE_WAIT_TIME
HTTP_X_HEROKU_QUEUE_DEPTH
HTTP_X_HEROKU_DYNOS_IN_USE]
# IN MS - from http request
class << self
def key(ms)
timestamp = ms.to_i
"#{PREFIX}:#{timestamp - (timestamp % TIME_STEP)}"
end
# IN SECS - for rails
def get(seconds)
get_by_ms seconds.to_i * 1000
end
def between(a, b)
first, last = [a,b].map{|n| n.to_i * 1000 }.sort
get_by_ms *(first..last).step(TIME_STEP)
end
def get_by_ms(*ms)
keys = ms.map{|k| key(k) }
values = $redis.mget(keys)
CSV.parse values.compact.join("")
end
end
def initialize(app)
@app = app
end
def call(env)
log_request env
@app.call env
end
def log_request(env)
data = KEYS.map {|k| env[k] }
key = self.class.key data.first
csv = CSV.generate_line data
$redis.append key, csv
$redis.expire key, EXPIRE_IN
rescue StandardError => e
Rails.logger.error(e)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment