13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/sql_genius/slow_query_monitor.rb', line 13
def subscribe!
ActiveSupport::Notifications.subscribe("sql.active_record") do |_name, start, finish, _id, payload|
duration_ms = ((finish - start) * 1000).round(1)
sql = payload[:sql].to_s
threshold = SqlGenius.configuration.slow_query_threshold_ms
next if duration_ms < threshold
next unless sql.match?(/\ASELECT\b/i)
next if sql.include?("SCHEMA")
next if sql.include?("EXPLAIN")
next if payload[:name] == "SCHEMA"
begin
redis = Redis.new(url: SqlGenius.configuration.redis_url)
entry = {
sql: sql.length > 10_000 ? sql[0, 10_000] : sql,
duration_ms: duration_ms,
timestamp: Time.now.iso8601,
name: payload[:name],
}.to_json
redis.lpush(redis_key, entry)
redis.ltrim(redis_key, 0, 199)
rescue => e
Rails.logger.debug("[sql_genius] Slow query logger error: #{e.message}") if defined?(Rails)
end
end
end
|