Ruby-on-rails Rails:记录异常的整个堆栈跟踪
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3484337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: Logging the entire stack trace of an exception
提问by Moiz Raja
I have been trying to figure out the right way to log a stack trace. I came across thislink which states that logger.error $!, $!.backtraceis the way to go but that does not work for me log_errordoes. 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.
我一直试图找出记录堆栈跟踪的正确方法。我遇到了这个链接,它指出logger.error $!, $!.backtrace是要走的路,但这对我不起作用 log_error。根据文档,我不知道将第二个参数传递给 error 方法是如何工作的,因为 rails 使用的 ruby 记录器只接受一个参数。
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?
谁能解释我缺少什么?任何关于错误的第二个论点是什么以及什么在吃它的见解?
回答by darkliquid
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.
如果您查看 ActiveSupport 中 BufferedLogger 类的源代码,您会看到第二个参数是“progname”。这仅在第一个参数为 nil 并且您没有给它块或块返回非真值时使用。
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
回答by kuboon
This is the answer.
这就是答案。
begin
raise
rescue => e
logger.error ([e.message]+e.backtrace).join($/)
end

