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

前端 未结 2 1031
忘掉有多难
忘掉有多难 2020-12-28 20:35

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\'r

相关标签:
2条回答
  • 2020-12-28 21:09

    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
    
    0 讨论(0)
  • 2020-12-28 21:11

    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 讨论(0)
提交回复
热议问题