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

前端 未结 2 1058
忘掉有多难
忘掉有多难 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: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
    

提交回复
热议问题