Skip to content

Instantly share code, notes, and snippets.

@pacoguzman
Created May 25, 2011 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pacoguzman/992102 to your computer and use it in GitHub Desktop.
Save pacoguzman/992102 to your computer and use it in GitHub Desktop.
Add sunspot solr instrumentation to a rails 3 app
module Sunspot
module Rails
module SolrInstrumentation
extend ActiveSupport::Concern
included do
alias_method :request_without_as_instrumentation, :request
alias_method :request, :request_with_as_instrumentation
end
module InstanceMethods
def request_with_as_instrumentation(path, params={}, *extra)
ActiveSupport::Notifications.instrument("request.rsolr",
{:path => path, :parameters => params}) do
request_without_as_instrumentation(path, params, *extra)
end
end
end
end
end
end
class RSolr::Client
include Sunspot::Rails::SolrInstrumentation
end
module Sunspot
module Rails
class LogSubscriber < ActiveSupport::LogSubscriber
def self.runtime=(value)
Thread.current["sorl_runtime"] = value
end
def self.runtime
Thread.current["sorl_runtime"] ||= 0
end
def self.reset_runtime
rt, self.runtime = runtime, 0
rt
end
def request(event)
self.class.runtime += event.duration
return unless logger.debug?
name = '%s (%.1fms)' % ["SOLR Resquest", event.duration]
# produces: path=/select parameters={fq: ["type:Offer"], q: bmw, fl: * score, qf: offer_supplier_name_text offer_summary_text offer_excerpt_text offer_body_text, defType: dismax, start: 0, rows: 20}
parameters = event.payload[:parameters].map { |k, v| "#{k}: #{color(v, BOLD, true)}" }.join(', ')
request = "path=#{event.payload[:path]} parameters={#{parameters}}"
debug " #{color(name, GREEN, true)} [ #{request} ]"
end
end
end
end
Sunspot::Rails::LogSubscriber.attach_to :rsolr
module Sunspot
module Rails
module Railties
module ControllerRuntime
extend ActiveSupport::Concern
protected
attr_internal :solr_runtime
def cleanup_view_runtime
# TODO only if solr is connected? if not call to super
solr_rt_before_render = Sunspot::Rails::LogSubscriber.reset_runtime
runtime = super
solr_rt_after_render = Sunspot::Rails::LogSubscriber.reset_runtime
self.solr_runtime = solr_rt_before_render + solr_rt_after_render
runtime - solr_rt_after_render
end
def append_info_to_payload(payload)
super
payload[:solr_runtime] = solr_runtime
end
module ClassMethods
def log_process_action(payload)
messages, solr_runtime = super, payload[:solr_runtime]
messages << ("Solr: %.1fms" % solr_runtime.to_f) if solr_runtime
messages
end
end
end
end
end
end
ActiveSupport.on_load(:action_controller) do
include Sunspot::Rails::Railties::ControllerRuntime
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment