Rails: Logging the entire stack trace of an exception

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

If you look at the source for the BufferedLogger class in ActiveSupport, you'll see that the second argument is 'progname'. This is used only when the first argument is nil and you have either given it no block or the block return a non-true value.

In essence, you can't use the second parameter to output additional stuff.

What you want to do is something more akin to:

begin
  raise
rescue => e
  logger.error e.message
  logger.error e.backtrace.join("\n")
end

Depending on how you have your logging setup, it might be better to iterate through each line of the backtrace and print it separately as certain loggers don't output newlines, in which case you'd do something like:

begin
  raise
rescue => e
  logger.error e.message
  e.backtrace.each { |line| logger.error line }
end

Solution 2 - Ruby on-Rails

This is the answer.

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

Solution 3 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMoiz RajaView Question on Stackoverflow
Solution 1 - Ruby on-RailsdarkliquidView Answer on Stackoverflow
Solution 2 - Ruby on-RailskuboonView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAlejandroVDView Answer on Stackoverflow