小编典典

如何在 Ruby on Rails 3.1 中禁用资产管道(链轮)消息的日志记录?

all

默认情况下,在 Ruby on Rails 3.1 (RC1) 下,Sprockets 在 (dev) 日志中往往非常冗长:

Started GET "/assets/application.css" for 127.0.0.1 at 2011-06-10 17:30:45 -0400
Compiled app/assets/stylesheets/application.css.scss  (5ms)  (pid 6303)


Started GET "/assets/application.js" for 127.0.0.1 at 2011-06-10 17:30:45 -0400
Compiled app/assets/stylesheets/default.css.scss  (15ms)  (pid 6303)

...
Started GET "/assets/default/header_bg.gif" for 127.0.0.1 at 2011-06-10 17:30:45 -0400
Served asset /default/header_logo.gif - 304 Not Modified  (7ms)  (pid 6303)
Served asset /default/header_bg.gif - 304 Not Modified  (0ms)  (pid 6246)
Served asset /default/footer_bg.gif - 304 Not Modified  (49ms)  (pid 6236)
...

我想降低详细程度或完全禁用它。

我假设有一种干净的方法来禁用或减少日志记录的详细程度,方法是在其中一个environment.rbdevelopment.rb类似的配置行中添加一个配置行来config.active_record.logger = nil使 ActiveRecord SQL 语句静音。


阅读 76

收藏
2022-03-28

共1个答案

小编典典

将以下代码放入config/initializers/quiet_assets.rb

if Rails.env.development?
  Rails.application.assets.try(:logger=, Logger.new('/dev/null'))
  Rails::Rack::Logger.class_eval do
    def call_with_quiet_assets(env)
      previous_level = Rails.logger.level
      Rails.logger.level = Logger::ERROR if env['PATH_INFO'] =~ %r{^/assets/}
      call_without_quiet_assets(env)
    ensure
      Rails.logger.level = previous_level
    end
    alias_method_chain :call, :quiet_assets
  end
end

更新:它现在也适用于 Ruby on Rails 3.2(之前的尝试修复before_dispatch,现在我们将使用根机架call

alias_method_chain更新:来自@macournoyer
https://github.com/rails/rails/issues/2639#issuecomment-6591735的适当的
Rack
中间件解决方案(而不是脆弱的)

2022-03-28