【问题标题】:How to disable activerecord cache logging in rails如何禁用rails中的activerecord缓存日志记录
【发布时间】:2012-07-07 13:59:54
【问题描述】:

我正在尝试禁用生产中缓存的日志记录。已成功让 SQL 停止记录查询,但缓存日志条目没有运气。生产日志中的示例行:

CACHE (0.0ms) SELECT `merchants`.* FROM `merchants` WHERE `merchants`.`id` = 1 LIMIT 1

我不想禁用所有日志记录,因为我希望 logger.debug 语句显示在生产日志中。 使用带有 Mysql 和 Apache 的 rails 3.2.1。 有什么建议吗?

【问题讨论】:

  • 我想知道如何使用 rails 2.3.5 做同样的事情

标签: ruby-on-rails caching activerecord logging


【解决方案1】:

Rails 5.1

# config/initializers/active_record_logger.rb

class CacheFreeLogger < ActiveSupport::Logger
  def add(severity, message = nil, progname = nil, &block)
    return true if progname&.include? "CACHE"
    super
  end
end

ActiveRecord::Base.logger = CacheFreeLogger.new(STDOUT)

【讨论】:

    【解决方案2】:

    我使用下面链接的帖子建议的方法使 CACHE 日志静音。

    我用一个包装器替换了默认的 ActiveRecod 记录器,该包装器过滤掉包含不需要的文本(即“CACHE”)的消息。

    首先,在config/initializers 内创建一个文件,例如active_record.rb,并在该文件内定义一个包装类并替换活动记录记录器,如下面的代码所示:

    # Implementation of logger that ignores messages containing forbidden words
    # here “CACHE” and "Settings Load"
    class CacheFreeLogger < ActiveSupport::TaggedLogging
    
      @@excluded = ['Settings Load','CACHE']
    
      def add(severity, message = nil, progname = nil, &block)
        if message.nil?
          if block_given?
            message = block.call
          else
            message = progname
            progname = nil #No instance variable for this like Logger
          end
        end
        if severity > Logger::DEBUG ||  !(@@excluded.map{|e| message.include? e}.include?(true))
            @logger.add(severity, "#{tags_text}#{message}", progname)
        end
      end
    end
    
    #Replace the existing logger with the filtering one
    ActiveRecord::Base.logger = CacheFreeLogger.new(ActiveRecord::Base.logger) if Rails.env.development?
    

    原来的帖子扩展了 Logger 而不是 TaggedLoggin 但它对我不起作用。

    这个方法是在博客中推荐的:http://heliom.ca/blog/posts/disable-rails-cache-logging

    【讨论】:

      【解决方案3】:

      在 SO 上有几个类似的问题(thisthisthis)都有类似的主题。您可以尝试将其放入初始化程序文件中:

      old_logger = ActiveRecord::Base.logger
      ActiveRecord::Base.logger = nil
      

      恢复记录器:

      ActiveRecord::Base.logger = old_logger; nil # nil just to suppress some garbage 
      

      【讨论】:

      • 您的答案与CACHE (0.0ms)-like 条目有什么关系?
      猜你喜欢
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 2018-12-24
      • 2020-01-17
      相关资源
      最近更新 更多