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

7
有没有办法更改ActionController::RoutingError的日志级别?我想把它从错误(Error)改成警告(Warning)。在谷歌上搜索了一圈还没找到解决方案...我只想将路由错误显示为警告,但不改变其他日志行为。一个可能的解决方法(或部分解决方法)在这里https://dev59.com/Em435IYBdhLWcg3wfQJ9#5386515中描述,但那并不完全是我想要的。在这种解决方案中,他们只是添加了一个捕获所有页面未找到错误的路由器,然后在catch-all-controller中处理它。但如果可能的话,我想能够仅更改日志严重性,因为这似乎更好地描述了我的意图...
2个回答

1

我在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://dev59.com/-ZHea4cB1Zd3GeqPnErB
# 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

我也很欣赏有趣的评论 :) 整天都在使用 wp-admin.php - JTE

0

您可以重写简单格式化程序,以便将错误记录为警告。

但是,我不建议采用这种方法,因为最终你会为应用程序视为错误/异常的操作记录警告消息。更优雅的选择是像您描述的那样拥有一个catch-all页面,由控制器捕获异常记录警告消息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接