13

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.

Christopher Stott
  • 1,408
  • 3
  • 15
  • 23
  • possible duplicate of [How to log something in Rails in an independent log file?](http://stackoverflow.com/questions/337739/how-to-log-something-in-rails-in-an-independent-log-file) – fl00r Mar 29 '11 at 15:30
  • 4
    I don't think it's a duplicate - it's a different question. About how to automatically split the standard log files into more fine grained parts - instead of manually logging to a separate file. – Christopher Stott Mar 29 '11 at 16:16

2 Answers2

7

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
Jenner La Fave
  • 1,327
  • 1
  • 9
  • 11
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
  • 1
    Is there a way to do this for exceptions in general? or to maybe log erb / controller errors to their own files too? – Christopher Stott Mar 29 '11 at 16:13
  • Posted how to do controllers/views. – Mike Lewis Mar 29 '11 at 16:18
  • 3
    How is it going to have only the errors? You're clearly logging an info and it ends up in exceptions.log? – Khash May 26 '11 at 17:48
  • 2
    This answer does not answer the question. It is off topic. It tells how to log to different files from different app layers / modules, not how to log debug/info/error/warn etc. level messages in to separate files. – Szymon Jeż Jun 27 '13 at 14:15
7

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
hallucinations
  • 3,424
  • 2
  • 16
  • 23
Michael Koper
  • 9,586
  • 7
  • 45
  • 59