ruby-on-rails - Rails - 如何更改 ActionController::RoutingError 的日志级别

标签 ruby-on-rails logging

有没有办法更改 ActionController::RoutingError 的日志级别?
我想将其从错误更改为警告。 google了一下,没找到解决办法。。。
我只想将路由错误显示为警告。但不会更改其他日志记录行为。
此处描述了一种可能的解决方法(或该解决方法的一部分)https://stackoverflow.com/a/5386515/10272但这不是我想要的。在这个解决方案中,他们只是为找不到页面的错误添加一个包罗万象的路由器,然后在包罗万象的 Controller 中处理它。但我希望能够改变日志严重性,如果可能的话,它似乎更好地描述了我的意图......

最佳答案

我在 Rails 5.2 中使用以下初始化器解决了这个问题:

# /config/initializers/routing_error_logger_defatalizer.rb

# Spammers and script kiddies hit the site looking for exploits
# which blows up our logs as we get a bunch of fatal errors for 404s on eg. "/wp-admin.php"
# This initializer changes the log level of RoutingErrors to 'warn' (so they still appear in logs but are not fatal)
# this means we can use logging notifications on eg. >= error without all the false positives
# ref: https://stackoverflow.com/questions/33827663/hide-actioncontrollerroutingerror-in-logs-for-assets
# ref: https://github.com/roidrage/lograge/issues/146#issuecomment-461632965
if Rails.env.production?
  module ActionDispatch
    class DebugExceptions
      alias_method :old_log_error, :log_error
      def log_error(request, wrapper)
        if wrapper.exception.is_a?  ActionController::RoutingError
          # Have prepended "[404]" to the message for easier log searches, otherwise it is the default Rails messaging
          # Full message eg. "[404] ActionController::RoutingError (No route matches [GET] \"/wp-login.php\")"
          logger(request).send(:warn, "[404] ActionController::RoutingError (#{wrapper.exception.message})")
          return
        else
          old_log_error request, wrapper
        end
      end
    end
  end
end

对于 Rails 4.2 使用:

if Rails.env.production?
  class ActionDispatch::DebugExceptions # Rails 4.2
    alias_method :old_log_error, :log_error
    def log_error(request, wrapper)
      if wrapper.exception.is_a?  ActionController::RoutingError
        # Have prepended "[404]" to the message for easier log searches, otherwise it is the default Rails messaging
        # Full message eg. "[404] ActionController::RoutingError (No route matches [GET] \"/wp-login.php\")"
        logger(request).send(:warn, "[404] ActionController::RoutingError (#{wrapper.exception.message})")
        return
      else
        old_log_error request, wrapper
      end
    end
  end
end

关于ruby-on-rails - Rails - 如何更改 ActionController::RoutingError 的日志级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9108565/

相关文章:

ruby-on-rails - rails 中是否有类似于 in_groups_of 的方法但用于哈希?

java - 记录约定

performance - 记录用户事件 IP 地址的成本

git - 使用 Bitbucket 去除 GIT 存储库上的提交

python - 如何动态地将变量传递给自定义 python 日志记录类中的类 __init__ 方法

ruby-on-rails - 有效地重命名 Rails 项目

css - Ruby on Rails 4 重新请求状态进度条

ruby-on-rails - 如何使用 join 编写 CanCan 能力?

ruby-on-rails - 使用数组的简单路由

java - 为什么 Java 中的记录器很少有 System.out.println 有的 .toString()?