2

我的 rails 应用程序每分钟都会对运行状况进行 ping 操作,除非出现错误,否则我希望将它们保留在日志之外。通过在 application_controller.rb 中设置记录器,我可以在 Rails 2.3.5 中做到这一点:

def logger
  if params[:__no_logging__] == 'true' && params[:controller] == 'welcome'
       && params[:action] == 'index'
    # ignore monitoring requests
    RAILS_MONITOR_NULL_LOGGER
  else
    RAILS_DEFAULT_LOGGER
  end
end

但这在 Rails 3.0.5 中不起作用

我已经能够通过在 Rails::Rack::Dispatch 中对 before_dispatch 和 after_dispatch 进行monkeypatching 来组合一个新的解决方案:

require 'active_support/core_ext/time/conversions'
module Rails
  module Rack
    # Log the request started and flush all loggers after it.
    class Logger
      include ActiveSupport::BufferedLogger::Severity

      def before_dispatch(env)
        request = ActionDispatch::Request.new(env)

        #path = request.filtered_path
        path = request.fullpath

        if request.path == '/' && request.parameters['__no_logging__'] == 'true'
          @log_level = logger.level
            logger.level = Logger::ERROR
            #logger.level = 3
        end

        info 
         "\n\nStarted #{request.request_method} 
             \"#{path}\" " \
             "for #{request.ip} at #{Time.now.to_default_s}"
      end
      def after_dispatch(env)
        logger.level = @log_level unless @log_level.nil?
        ActiveSupport::LogSubscriber.flush_all!
      end
        end
    end
end

我把补丁放在 config/initializers/monkey_patch.rb

这完全符合我的需要,我在日志中没有看到这个请求:

http://mydomain.com?__no_logging__=true

但所有其他请求仍保留在日志中不受影响

但是仍然存在两个问题:

1.我需要注释掉:

path = request.filtered_path

因为它会导致这个错误:

ERROR NoMethodError: undefined method `filtered_path' for #<ActionDispatch::Request:0x105b4c0e8>
/ce_development/Rails/g3/config/initializers/monkey_patches.rb:52:in `before_dispatch'
/ce_development/Rails/g3/.bundle/ruby/1.8/gems/railties-3.0.5/lib/rails/rack/logger.rb:12:in `call'
...

我现在明白这不是问题。我正在使用的 Rails 3.0.5 中不存在有问题的方法“request.filtered_pa​​th”。我无意中从 Rails 3.1.0.beta 复制了我的类,它确实定义了过滤路径。Rails 3.0.5 使用 request.fullpath ,如上所示。

2.我需要注释掉

logger.level = Logger::ERROR

因为它会导致这个错误:

ERROR NameError: uninitialized constant Rails::Rack::Logger::ERROR
/ce_development/Rails/g3/config/initializers/monkey_patches.rb:57:in `before_dispatch'
/ce_development/Rails/g3/.bundle/ruby/1.8/gems/railties-3.0.5/lib/rails/rack/logger.rb:12:in `call'
...

我通过在上面添加这一行解决了第二个问题

include ActiveSupport::BufferedLogger::Severity

我是猴子补丁的新手,我不知道如何在补丁中定义过滤路径或 Logger::Error。我尝试过其他要求,但还没有运气。

我还想对在我的项目中使用这个猴子补丁的稳健性提出任何建议。有一个更好的方法吗?

我知道有些人不相信更改日志,但我不希望日志中出现所有这些 ping,除非在请求期间出现错误。

4

1 回答 1

0

此处描述了 Rails 3 中 Logger 被自定义 Logger 替换的可能解决方案:Silencing the Rails log on per-action based和此处:How can I disable logging in Ruby on Rails on per-action based? . 我必须添加require 'rails/all'custom_logger.rb课程中才能使其正常工作。

于 2011-10-27T13:43:14.047 回答