Module: Metrician::QueryInterceptor

Defined in:
lib/metrician/reporters/active_record.rb

Constant Summary collapse

COMMAND_EXP =
/^(select|update|insert|delete|show|begin|commit|rollback|describe)/i
SQL_EXP =
/#{COMMAND_EXP} (?:into |from |.+? from )?(?:[`"]([a-z_]+)[`"])?/i
OTHER =
"other".freeze
QUERY_METRIC =
"database.query"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(instrumented_class) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/metrician/reporters/active_record.rb', line 25

def self.included(instrumented_class)
  return if instrumented_class.method_defined?(:log_without_metrician)
  instrumented_class.class_eval do
    alias_method :log_without_metrician, :log
    alias_method :log, :log_with_metrician
    protected :log
  end
end

Instance Method Details

#log_with_metrician(*args, &block) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/metrician/reporters/active_record.rb', line 34

def log_with_metrician(*args, &block)
  start_time = Time.now.to_f
  sql, name, _binds = args
  sql = sql.dup.force_encoding(Encoding::BINARY)
  config = Metrician.configuration[:database]
  metrics = []
  metrics << QUERY_METRIC if config[:query][:enabled]
  if [:command, :table, :command_and_table].any?{ |key| config[key][:enabled] }
    command, table = parse_sql(sql)
    metrics << "database.#{command}" if config[:command][:enabled] && command
    metrics << "database.#{table}" if config[:table][:enabled] && table
    metrics << "database.#{command}.#{table}" if config[:command_and_table][:enabled] && command && table
  end
  begin
    log_without_metrician(*args, &block)
  ensure
    duration = Time.now.to_f - start_time
    metrics.each { |m| Metrician.gauge(m, duration) }
  end
end

#parse_sql(sql) ⇒ Object



55
56
57
58
59
60
# File 'lib/metrician/reporters/active_record.rb', line 55

def parse_sql(sql)
  match = sql.match(SQL_EXP)
  command = (match && match[1].downcase) || OTHER
  table = (match && match[2] && match[2].downcase)
  [command, table]
end