开发者

How can I log Rails errors into a separate log file?

开发者 https://www.devze.com 2023-02-21 02:01 出处:网络
Our production logs are long and con开发者_运维技巧tain a lot more than just errors. I\'d like a second log file with just the errors/exceptions in.

Our production logs are long and con开发者_运维技巧tain a lot more than just errors. I'd like a second log file with just the errors/exceptions in.

Is this possible?

We're using rails 2.x

Thanks.


For example, to log all ActiveRecord::Base errors in a file called log/exceptions.log

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

For controllers and view(because ActionView logger doesn't have it's own logger, so it depends on the ActionController logger):

ActionController::Base.logger = new_logger


Try the following. Put the rescue_from method in your controller.

I haven't tested this. But maybe it puts you in the right direction

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

If you use Rails 2.1 (also not tested)

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
0

精彩评论

暂无评论...
验证码 换一张
取 消