【问题标题】:Output line number in Rails log fileRails 日志文件中的输出行号
【发布时间】:2010-02-15 20:24:24
【问题描述】:

Rails Guide的调试中,我发现我可以使用这个简单的方法自定义输出到我的日志文件:

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

我决定使用它来跟踪变量如何变化并通过流控制。

我希望能够看到调用logger#debug 方法的代码行号。像这样的:

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

【问题讨论】:

    标签: ruby-on-rails debugging line-numbers


    【解决方案1】:

    在 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
    

    【讨论】:

      【解决方案2】:
      logger.debug "Person attributes hash: #{@person.attributes.inspect} from line #{__LINE__}"
      

      【讨论】:

      • 看我的第一句话。 Stackoverflow 的消息解析器不会连续显示两个下划线(隐藏它们或以其他方式吞噬它们;可能使下划线之间的部分消息变为粗体)。
      • 好的,太好了!谢谢!我不知道你的意思是 SO 的解析器。所以用这个:dpaste.com/159599
      【解决方案3】:

      从 Rails 5 开始,现在通过以下方式烘焙:

      ActiveRecord::Base.verbose_query_logs = true
      

      更多信息请见the documentation

      【讨论】:

        猜你喜欢
        • 2017-12-10
        • 2016-03-29
        • 2012-04-21
        • 1970-01-01
        • 2015-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多