如何将Rails错误记录到单独的日志文件中?
我们的生产日志很长,包含的不仅仅是错误。 我想要一个只有错误/exception的第二个日志文件。
这可能吗?
我们正在使用rails 2.x.
谢谢。
例如,要在名为log / exceptions.log的文件中记录所有ActiveRecord :: Base错误
new_logger = Logger.new('log/exceptions.log') new_logger.level = Logger::ERROR new_logger.error('THIS IS A NEW EXCEPTION!') ActiveRecord::Base.logger = new_logger
对于控制器和视图(因为ActionView记录器没有它自己的记录器,所以它依赖于ActionController记录器):
ActionController::Base.logger = new_logger
请尝试以下方法。 将rescue_from方法放在控制器中。
我没有测试过这个。 但也许它会让你朝着正确的方向前进
class ApplicationController < ActionController::Base rescue_from StandardError do |exception| new_logger = Logger.new('log/exceptions.log') new_logger.info('THIS IS A NEW EXCEPTION!') new_logger.info(exception.message) new_logger.info(exception.backtrace) # Raise it anyway because you just want to put it in the log raise exception end end
如果您使用Rails 2.1(也未测试)
class ApplicationController < ActionController::Base def rescue_action_in_public(exception) new_logger = Logger.new('log/exceptions.log') new_logger.info('THIS IS A NEW EXCEPTION!') new_logger.info(exception.message) new_logger.info(exception.backtrace) # Raise it anyway because you just want to put it in the log raise exception end end