Output line number in Rails log file

2019-04-29 11:13发布

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}"

2条回答
小情绪 Triste *
2楼-- · 2019-04-29 11:50
logger.debug "Person attributes hash: #{@person.attributes.inspect} from line #{__LINE__}"
查看更多
男人必须洒脱
3楼-- · 2019-04-29 11:57

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
查看更多
登录 后发表回答