Skip to content

Instantly share code, notes, and snippets.

@kares
Last active March 23, 2022 09:40
Show Gist options
  • Select an option

  • Save kares/e36a4d992e978059eb5f4f470cface41 to your computer and use it in GitHub Desktop.

Select an option

Save kares/e36a4d992e978059eb5f4f470cface41 to your computer and use it in GitHub Desktop.

Revisions

  1. kares revised this gist Nov 21, 2016. 1 changed file with 7 additions and 2 deletions.
    9 changes: 7 additions & 2 deletions slow_query_log.rb
    Original file line number Diff line number Diff line change
    @@ -2,8 +2,13 @@

    class SlowQueryLog < ActiveSupport::LogSubscriber

    @@threshold = Rails.configuration.slow_query_log_threshold_in_ms
    @@threshold = @@threshold.to_i == 0 ? nil : @@threshold.to_i if @@threshold
    if Rails.configuration.respond_to?(:slow_query_log_threshold_in_ms)
    if @@threshold = Rails.configuration.slow_query_log_threshold_in_ms
    @@threshold = @@threshold.to_i == 0 ? nil : @@threshold.to_i
    end
    else
    @@threshold = nil
    end

    def sql(event)
    return unless duration_ms = event.duration
  2. kares revised this gist Nov 21, 2016. No changes.
  3. kares created this gist Nov 21, 2016.
    41 changes: 41 additions & 0 deletions slow_query_log.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    require 'active_record/log_subscriber'

    class SlowQueryLog < ActiveSupport::LogSubscriber

    @@threshold = Rails.configuration.slow_query_log_threshold_in_ms
    @@threshold = @@threshold.to_i == 0 ? nil : @@threshold.to_i if @@threshold

    def sql(event)
    return unless duration_ms = event.duration
    return if ! @@threshold || @@threshold > duration_ms

    payload = event.payload; name = payload[:name]

    return if name.eql? 'EXPLAIN'; return if name.eql? 'SCHEMA'

    if ( binds = payload[:binds] ) && ! binds.empty?
    binds = " #{binds.map { |col,v| render_bind(col, v) }.inspect}"
    end

    log "#{name} (#{event.duration.round(1)}ms) #{payload[:sql]}#{binds}"
    end

    def log(msg)
    logger = ActiveRecord::Base.logger
    logger && logger.warn("[slow-query] #{msg}")
    end

    private

    def render_bind(column, value) # from ActiveRecord::LogSubscriber
    return [nil, value] unless column
    if column.binary?
    value = value[:value] if value.is_a?(Hash)
    value = value ? "<#{value.bytesize} bytes of binary data>" : "<NULL binary data>"
    end
    [column.name, value]
    end

    end

    SlowQueryLog.attach_to :active_record