项目上线以后,难免都会遇到爬虫,或某些奇怪的东西扫描网站,然后我们的 production.log 就会出现很多这样的错误信息:
Started GET "/register.php" for 110.75.186.226 at 2013-05-23 05:47:32 +0800
ActionController::RoutingError (No route matches [GET] "/register.php"):
actionpack (3.2.13) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
actionpack (3.2.13) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
railties (3.2.13) lib/rails/rack/logger.rb:32:in `call_app'
railties (3.2.13) lib/rails/rack/logger.rb:16:in `block in call'
activesupport (3.2.13) lib/active_support/tagged_logging.rb:22:in `tagged'
railties (3.2.13) lib/rails/rack/logger.rb:16:in `call'
actionpack (3.2.13) lib/action_dispatch/middleware/request_id.rb:22:in `call'
rack (1.4.5) lib/rack/methodoverride.rb:21:in `call'
rack (1.4.5) lib/rack/runtime.rb:17:in `call'
activesupport (3.2.13) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.4.5) lib/rack/lock.rb:15:in `call'
rack-cache (1.2) lib/rack/cache/context.rb:136:in `forward'
rack-cache (1.2) lib/rack/cache/context.rb:245:in `fetch'
rack-cache (1.2) lib/rack/cache/context.rb:185:in `lookup'
rack-cache (1.2) lib/rack/cache/context.rb:66:in `call!'
rack-cache (1.2) lib/rack/cache/context.rb:51:in `call'
railties (3.2.13) lib/rails/engine.rb:479:in `call'
railties (3.2.13) lib/rails/application.rb:223:in `call'
railties (3.2.13) lib/rails/railtie/configurable.rb:30:in `method_missing'
虽然表面上没有什么大问题,但是这种错误的请求打乱了我们的 Log,尤其是当你用了 exception_notification 这类东西做提醒的时候,你的日常工作将会被这些打乱(当然可以在提交前屏蔽 ActionController::RoutingError
的错误,那是另外回事)。
routes.rb 的最后加上
match '*path', via: :all, to: 'home#error_404'
home_controller.rb 加上
def error_404
render file: "#{Rails.root}/public/404.html", status: 404, layout: false
end
然后 Log 里面干净了:
Started HEAD "/register.php" for 127.0.0.1 at 2014-09-10 19:05:41 +0800
Processing by HomeController#error_404 as */*
Rendered public/404.html (0.6ms)
Completed 404 Not Found in 10ms (Views: 10ms | ActiveRecord: 0.0ms)