Libor Zahrádka Libor Zahrádka - 2 months ago 26
Ruby Question

Rails custom error Logging

I'm really wondering if there is any way, how to create custom Logging with instant sync for any error on Rails..

So it should be same as

production.log
but just for error messages.
And for example then I can use:
tail -f log/error-prod.log


Thanks!

Answer

You could capture errors within the ApplicationController with rescue_from and then write the error to a log before re-raising the error.

class ApplicationController < ActionController::Base
  rescue_from StandardError, with: :log_error

  private

  def log_error(e)
    error_log.info(e.message)
    raise(e)
  end

  def error_log
    @error_log ||= Logger.new(Rails.root.join('log', "error-#{Rails.env.to_s}.log"))
  end
end
Comments