7

From the Rails Guide on debugging, I found that I can customize output to my log files using this simple method:

logger.debug "Person attributes hash: #{@person.attributes.inspect}"

I decided use this to track how a variable changes and goes through flow control.

I would like to be able to see the line number of my code where logger#debug method was called. Something like this:

logger.debug "Person attributes hash: #{@person.attributes.inspect} from line #{LINE_NUMBER_VAR}"
user94154
  • 16,176
  • 20
  • 77
  • 116

3 Answers3

10

Use a decorator on Logger:

class LoggerDecorator
  def initialize(logger)
    @logger = logger
  end

  %w{debug info warn error fatal}.each do |method|
    eval(<<-eomethod)
      def #{method}(msg)
        @logger.#{method}(position) {msg}
      end
    eomethod
  end

  private
  def position
    caller.at(1).sub(%r{.*/},'').sub(%r{:in\s.*},'')
  end
end
Roman
  • 13,100
  • 2
  • 47
  • 63
8
logger.debug "Person attributes hash: #{@person.attributes.inspect} from line #{__LINE__}"
huntar
  • 1,072
  • 11
  • 9
DNNX
  • 6,215
  • 2
  • 27
  • 33
  • See my fisrt sentence. Stackoverflow's message parser don't shows two underscores in a row (hides them or eats up somehow else; maybe makes part of message between underscores bold). – DNNX Feb 15 '10 at 20:33
  • 1
    ok great! thanks! I didn't know you meant SO's parsers. so use this: http://dpaste.com/159599/ – user94154 Feb 15 '10 at 20:35
4

As of Rails 5, this is now baked in via:

ActiveRecord::Base.verbose_query_logs = true

See the documentation for more

Anthony
  • 15,435
  • 4
  • 39
  • 69