开发者

Rails: Logging the entire stack trace of an exception

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 ign开发者_运维问答ored.

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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜