生产环境下,由于经常会有爬虫爬网站,而且之前的很多链接都已经失效了,因此日志中经常会出现以前的链接找不到导致产生许多路由错误,或者文章改了个名导致产生数据库记录未找到异常,导致日志很乱。可以用下面的办法来简单的解决
路由错误
这个是由于爬虫用以前的链接来爬网站,但是以前的链接大多数已经失效了,所以会产生许多路由错误。
吸收所有未匹配路由
在路由的最后一行,吸收所有前面未匹配的访问。
match '*path', via: :all, to: 'pages#error_404'
然后在 pages#error_404
里返回 404 就行了
class PagesController < ApplicationController def error_404 render file: "#{Rails.root}/public/404.html", status: 404, layout: false endend
使用 rescue_from
也可以在 ApplicationController
中使用 rescue_from
捕获所有 ActionController::RoutingError
异常
class ApplicationController < ActionController::Base rescue_from ActionController::RoutingError, with: :render_error_404 private def render_error_404 render file: "#{Rails.root}/public/404.html", status: 404, layout: false endend
数据库记录未找到
这个也用 rescue_from
捕获 Mongoid::Errors::DocumentNotFound
异常就行了(ActiveRecord
是 ActiveRecord::RecordNotFound
)
class ApplicationController < ActionController::Base rescue_from Mongoid::Errors::DocumentNotFound, with: :render_error_404end
仅在生产环境下使用
通常我们只需要在生产环境下这样,而在开发环境下处于调试考虑,我们希望它在日志中尽可能的有更多的输出,因此可以只在生产环境下使用。
路由
if Rails.env.production? match '*path', via: :all, to: 'pages#error_404'end
ApplicationController
class ApplicationController if Rails.env.production? rescue_from ActionController::RoutingError, with: :render_error_404 rescue_from Mongoid::Errors::DocumentNotFound, with: :render_error_404 endend
本文出自:http://blog.sloger.info/, 原文地址:http://sloger.info/posts/two-tips-make-rails-log-more-clean, 感谢原作者分享。 记忆像是倒在手心里的水,不论是摊平还是握紧,