Created
May 12, 2011 15:23
-
-
Save tjsingleton/968735 to your computer and use it in GitHub Desktop.
Middleware that logs heroku requests into redis.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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