Rails: Logging the entire stack trace of an exception

Viewed 103507

I have been trying to figure out the right way to log a stack trace. I came across this link which states that logger.error $!, $!.backtrace is the way to go but that does not work for me log_error does. As per documentation I do not see how passing a second argument to the error method would work anyway because the ruby logger that rails uses only accepts a single argument.

Strangely (or maybe not) the second argument is accepted without any interpreter complaints. However anything that I pass to it is ignored.

Can anyone explain what I am missing? Any insight into what the second argument to error is for and what is eating it?

3 Answers

This is the answer.

begin
  raise
rescue => e
  logger.error ([e.message]+e.backtrace).join($/)
end

Based on kuboon's answer I find this logging format to be generic and useful to categorise errors in my logfiles:

begin
  raise
rescue StandardError => e
  Rails.logger.error (["#{self.class} - #{e.class}: #{e.message}"]+e.backtrace).join("\n")
end
Related