module TransactionLogger::ClassMethods

Public Instance Methods

add_transaction_log(method, options={}) click to toggle source

Registers a method with the TransactionLogger, which will begin tracking the

logging within the method and it's nested methods. These logs are collected
under one transaction, and if the level threshold is broken or when an error
is raised, the collected logs are pushed to the configured logger as a JSON
hash.

By registering multiple methods as transactions, each method becomes it's
own transaction.

@param method [Symbol] The method you want to register with TransactionLogger @param options [Hash] Additional options, such as custom transaction name and context

# File lib/transaction_logger.rb, line 28
def add_transaction_log(method, options={})
  old_method = instance_method method

  options[:prefix] = TransactionLogger::Configure.instance_variable_get :@prefix
  options[:logger] = TransactionLogger::Configure.instance_variable_get :@logger
  options[:level_threshold] = TransactionLogger::Configure.instance_variable_get :@level_threshold

  define_method method do |*params|
    context = options[:context]

    if context.is_a? Proc
      begin
        context = instance_exec(&context)
      rescue => e
        context = "TransactionLogger: couldn't evaluate context: #{e.message}"
        # Write an error to the untrapped logger
        logger.error context
        logger.error e.backtrace.take(10).join "\n"
      end
    end

    TransactionManager.start options, lambda { |transaction|
      transaction.name = options[:name]
      transaction.name ||= "#{old_method.bind(self).owner}#{method.inspect}"
      transaction.context = context || {}

      # Check for a logger on the instance
      if methods.include? :logger
        logger_method = method(:logger).unbind
      # Check for a logger on the class
      elsif self.class.methods.include? :logger
        logger_method = self.class.method :logger
      end

      # Trap the logger if we've found one
      if logger_method
        method_info = {}
        method_info[:logger_method] = logger_method
        method_info[:calling_method] = caller_locations(1, 1)[0].label
        method_info[:includer] = self

        TransactionLogger::Helper.trap_logger method, transaction, method_info
      end

      old_method.bind(self).call(*params)
    }
  end
end