Sha256: 4e88f84353cce17d1b05bd4c5e7304af1f8ab572b87a51ffa9b62e6740ef4dbc

Contents?: true

Size: 1.51 KB

Versions: 28

Compression:

Stored size: 1.51 KB

Contents

module Simple
  module SQL
    module Logging
      extend self

      # The logger object.
      #
      # If no logger was set via <tt>Simple::SQL::Logging.logger = <foo></tt>
      # this returns a default logger.
      def logger
        @logger ||= default_logger
      end

      # The logger object.
      def logger=(logger)
        @logger = logger
      end

      private

      def default_logger
        # return the ActiveRecord logger, if it exists.
        if defined?(ActiveRecord)
          logger = ActiveRecord::Base.logger
          return logger if logger
        end

        # returns a stderr_logger
        @stderr_logger ||= begin
          logger = Logger.new(STDERR)
          logger.level = Logger::INFO
          logger
        end
      end

      public

      extend Forwardable
      delegate [:debug, :info, :warn, :error, :fatal] => :logger

      def yield_logged(sql, *args, &_block)
        r0 = Time.now
        rv = yield
        realtime = Time.now - r0
        debug "[sql] %.3f secs: %s" % [realtime, format_query(sql, *args)]
        rv
      rescue StandardError => e
        realtime = Time.now - r0
        warn "[sql] %.3f secs: %s:\n\tfailed with error %s" % [realtime, format_query(sql, *args), e.message]
        raise
      end

      private

      def format_query(sql, *args)
        sql = sql.gsub(/\s*\n\s*/, " ").gsub(/(\A\s+)|(\s+\z)/, "")
        return sql if args.empty?
        args = args.map(&:inspect).join(", ")
        sql + " w/args: #{args}"
      end
    end
  end
end

Version data entries

28 entries across 28 versions & 1 rubygems

Version Path
simple-sql-0.4.28 lib/simple/sql/logging.rb
simple-sql-0.4.27 lib/simple/sql/logging.rb
simple-sql-0.4.26 lib/simple/sql/logging.rb
simple-sql-0.4.25 lib/simple/sql/logging.rb
simple-sql-0.4.24 lib/simple/sql/logging.rb
simple-sql-0.4.23 lib/simple/sql/logging.rb
simple-sql-0.4.22 lib/simple/sql/logging.rb
simple-sql-0.4.21 lib/simple/sql/logging.rb
simple-sql-0.4.20 lib/simple/sql/logging.rb
simple-sql-0.4.19 lib/simple/sql/logging.rb
simple-sql-0.4.18 lib/simple/sql/logging.rb
simple-sql-0.4.17 lib/simple/sql/logging.rb
simple-sql-0.4.16 lib/simple/sql/logging.rb
simple-sql-0.4.15 lib/simple/sql/logging.rb
simple-sql-0.4.14 lib/simple/sql/logging.rb
simple-sql-0.4.13 lib/simple/sql/logging.rb
simple-sql-0.4.12 lib/simple/sql/logging.rb
simple-sql-0.4.11 lib/simple/sql/logging.rb
simple-sql-0.4.10 lib/simple/sql/logging.rb
simple-sql-0.4.9 lib/simple/sql/logging.rb