Sha256: 5beab599657a2ec9ad97c617ae47fc6ca4496ec6a1bb032ef78db70dd55fc406

Contents?: true

Size: 1.97 KB

Versions: 5

Compression:

Stored size: 1.97 KB

Contents

require "securerandom"

module RailsLogstasher
  module ActiveRecord
    class LogSubscriber < ::ActiveSupport::LogSubscriber

      def self.runtime=(value)
        Thread.current["active_record_sql_runtime"] = value
      end

      def self.runtime
        Thread.current["active_record_sql_runtime"] ||= 0
      end

      def self.reset_runtime
        rt, self.runtime = runtime, 0
        rt
      end

      def initialize
        super
      end

      def sql(event)
        self.class.runtime += event.duration
        return unless logger.debug?

        payload = event.payload

        return if 'SCHEMA' == payload[:name]

        sql_entry = {}
        sql_entry['name'] = payload[:name]
        sql_entry['duration'] = event.duration
        sql_entry['sql']= payload[:sql].squeeze(' ')

        binds = nil

        unless (payload[:binds] || []).empty?
          binds = "  " + payload[:binds].map { |col,v|
            [col.name, v]
          }.inspect
        end

        sql_entry['binds'] = binds unless binds.nil?

        write_entry sql_entry
      end

      def identity(event)
        return unless logger.debug?

        payload = event.payload

        sql_entry = {}
        sql_entry['name'] = payload[:name]
        sql_entry['line'] = payload[:line]
        sql_entry['duration'] = payload[:duration]

        write_entry sql_entry
      end

    private

      def write_entry(sql_entry)
        entry = log_entry
        entry.fields['sql'] ||= []
        entry.fields['sql'] << sql_entry
        entry.write(false)
      end

      def logger
        ::ActiveRecord::Base.logger
      end

      def log_entry
        RailsLogstasher.log_entries[Thread.current] ||
          RailsLogstasher::Event.new(Rails.logger, false).tap do |entry|
          entry.fields['uuid'] = SecureRandom.uuid
          #TODO Should really move this into the base logger
          entry.source = Socket.gethostname
          entry.type = "rails_json_log"
        end
      end

    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rails-logstasher-0.1.4 lib/rails-logstasher/active_record/log_subscriber.rb
rails-logstasher-0.1.3 lib/rails-logstasher/active_record/log_subscriber.rb
rails-logstasher-0.1.2 lib/rails-logstasher/active_record/log_subscriber.rb
rails-logstasher-0.1.1 lib/rails-logstasher/active_record/log_subscriber.rb
rails-logstasher-0.1.0 lib/rails_logstasher/active_record/log_subscriber.rb