lib/td/logger/agent/access_log.rb in td-logger-0.2.4 vs lib/td/logger/agent/access_log.rb in td-logger-0.2.5

- old
+ new

@@ -2,12 +2,12 @@ module TreasureData module Logger module Agent ACCESS_LOG_PARAM_ENV = - if defined? Rails - if Rails.respond_to?(:version) && Rails.version =~ /^3/ + if defined? ::Rails + if ::Rails.respond_to?(:version) && ::Rails.version =~ /^3/ # Rails 3 'action_dispatch.request.path_parameters' else # Rails 2 'action_controller.request.path_parameters' @@ -16,56 +16,64 @@ # Rack default 'rack.routing_args' end ACCESS_LOG_PRESET_PARAM_KEYS = { - 'controller' => :controller, - 'action' => :action, + :controller => :controller, + :action => :action, } - ACCESS_LOG_PRESET_ENV_KEYS = { - 'ip' => 'REMOTE_ADDR', - 'method' => 'REQUEST_METHOD', - 'uri' => 'REQUEST_URI', - 'referer' => 'HTTP_REFERER', - 'ua' => 'HTTP_USER_AGENT' - } - def self.enable_access_log(tag) Middleware.before do |env| - data = {} - Thread.current['td.access_log'] = data - env['td.access_log'] = data + record = {} + Thread.current['td.access_log'] = record + env['td.access_log'] = record env['td.access_time'] = Time.now end Middleware.after do |env,result| - data = env['td.access_log'] || {} - access_time = env['td.access_time'] - - # add 'elapsed' column - if access_time - elapsed = Time.now - access_time - data['elapsed'] = elapsed - # set 'time' column to access time - data['time'] = access_time + req = env['action_dispatch.request'] + if !req || !req.is_a?(Rack::Request) + req = Rack::Request.new(env) end - ACCESS_LOG_PRESET_ENV_KEYS.each_pair {|key,val| - data[key] ||= env[val] if env[val] - } + # ignore OPTIONS request + if req.request_method != "OPTIONS" + record = env['td.access_log'] || {} + access_time = env['td.access_time'] - m = env[ACCESS_LOG_PARAM_ENV] - ACCESS_LOG_PRESET_PARAM_KEYS.each_pair {|key,val| - data[key] ||= m[val] if m[val] - } + # add 'elapsed' column + if access_time + elapsed = Time.now - access_time + record[:elapsed] = elapsed + # set 'time' column to access time + record[:time] = access_time + end - # result code - data['status'] ||= result[0].to_i + record[:method] ||= req.request_method + record[:ip] ||= (env['action_dispatch.remote_ip'] || req.ip).to_s + record[:uri] ||= env['REQUEST_URI'].to_s if env['REQUEST_URI'] + record[:referer] ||= env['HTTP_REFERER'].to_s if env['HTTP_REFERER'] + record[:ua] ||= env['HTTP_USER_AGENT'].to_s if env['HTTP_USER_AGENT'] - TreasureData.log(tag, data) + m = env[ACCESS_LOG_PARAM_ENV] + ACCESS_LOG_PRESET_PARAM_KEYS.each_pair {|key,val| + record[key] ||= m[val] if m[val] + } + + # result code + record[:status] ||= result[0].to_i + + TreasureData.log(tag, record) + end end end end end +end + +module TreasureData + def self.access_log + Thread.current['td.access_log'] + end end