How can I log Rails errors into a separate log fil

2019-02-02 11:07发布

Our production logs are long and contain 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.

2条回答
对你真心纯属浪费
2楼-- · 2019-02-02 11:45

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
查看更多
干净又极端
3楼-- · 2019-02-02 12:01

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
查看更多
登录 后发表回答