如何在每个操作的基础上禁用 Ruby on Rails 的登录? [英] How can I disable logging in Ruby on Rails on a per-action basis?

查看:25
本文介绍了如何在每个操作的基础上禁用 Ruby on Rails 的登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Rails 应用程序,它有一个动作,它被频繁调用,在我开发时很不方便,因为它会导致很多我不关心的额外日志输出.我怎样才能让 rails 不为这一个动作记录任何东西(控制器、动作、参数、完成时间等)?我也想在 RAILS_ENV 上对其进行条件化,这样生产中的日志就完成了.

I have a Rails application which has an action which is invoked frequently enough to be inconvenient when I am developing, as it results in a lot of extra log output I don't care about. How can I get rails not to log anything (controller, action, parameters, complection time, etc.) for just this one action? I'd like to conditionalize it on RAILS_ENV as well, so logs in production are complete.

谢谢!

推荐答案

结果比我预期的要困难得多,因为 rails 确实没有提供任何钩子来做到这一点.相反,您需要包装 ActionController::Base 的一些内容.在我的控制器的公共基类中,我做

The answer turns out to be a lot harder than I expected, since rails really does provide no hook to do this. Instead, you need to wrap some of the guts of ActionController::Base. In the common base class for my controllers, I do

def silent?(action)
  false
end

# this knows more than I'd like about the internals of process, but
# the other options require knowing even more.  It would have been
# nice to be able to use logger.silence, but there isn't a good
# method to hook that around, due to the way benchmarking logs.

def log_processing_with_silence_logs
  if logger && silent?(action_name) then
    @old_logger_level, logger.level = logger.level, Logger::ERROR
  end

  log_processing_without_silence_logs
end

def process_with_silence_logs(request, response, method = :perform_action, *arguments)
  ret = process_without_silence_logs(request, response, method, *arguments)
  if logger && silent?(action_name) then
    logger.level = @old_logger_level
  end
  ret
end

alias_method_chain :log_processing, :silence_logs
alias_method_chain :process, :silence_logs

然后,在控制器中使用我想禁止登录的方法:

then, in the controller with the method I want to suppress logging on:

def silent?(action)
  RAILS_ENV == "development" && ['my_noisy_action'].include?(action)
end

这篇关于如何在每个操作的基础上禁用 Ruby on Rails 的登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆