class Rack::HTTPLogger

Constants

VERSION

Public Class Methods

new(app, options = {}) click to toggle source
# File lib/rack/http-logger.rb, line 5
def initialize(app, options = {})
  @app = app

  @stream = options[:stream] || $stdout
  @stream.sync = true unless options.fetch(:sync, true)
  @source = options[:source] || "rack-http-logger"

  @method = options[:method] ? "#{options[:method]}".upcase : "LOG"
  @path = options[:path] || "/"
end

Public Instance Methods

call(env) click to toggle source
# File lib/rack/http-logger.rb, line 16
def call(env)
  request = Rack::Request.new(env)

  return @app.call(env) unless request.request_method == @method and request.path == @path

  if request.media_type == "application/json" and (body = request.body.read).length.nonzero?
    log JSON.parse(body)
  else
    log request.params
  end

  [201, {"Content-Type" => "text/plain"}, []]
end

Private Instance Methods

flatten(hash, k = []) click to toggle source
# File lib/rack/http-logger.rb, line 40
def flatten(hash, k = [])
  return {Array(k) => hash} unless hash.is_a?(Hash)
  hash.inject({}){ |h, v| h.merge! flatten(v[-1], k + [v[0]]) }
end
log(parameters) click to toggle source
# File lib/rack/http-logger.rb, line 32
def log(parameters)
  return if parameters.nil? or parameters.empty?

  measures = flatten(parameters).collect{|keys, value| "#{keys.collect(&:to_s).join('.')}=#{value}"}

  @stream.puts ["source=#{@source}", *measures].join(" ")
end