在Ruby中自动记录异常

Chr*_*nch 6 ruby logging exception-handling

是否有一个库或简单的方法来捕获Ruby程序中抛出的异常并将其记录到文件中?我查看了log4rlogger,但两者的文档都没有提供我将如何做到这一点的任何示例.我远程运行这个程序并失去stdout和stderr的句柄,如果这些信息有帮助的话.

你会推荐什么?

Mar*_*usQ 14

如果你想在野外散步,试试这个:

class Exception
  alias real_init initialize
  def initialize(*args)
    real_init *args
    # log the error (self) or its args here
  end
end
Run Code Online (Sandbox Code Playgroud)

这将在创建时拦截新异常对象的创建.


Aug*_*aas 5

从救援Exception。这样的事情可能是有道理的:

begin
  # run your code here ..
rescue Exception => exception
  # logger.error(...) ....
  raise exception
end
Run Code Online (Sandbox Code Playgroud)

这将记录该异常,然后重新引发它,以便应用程序除记录日志外还实际引发错误。

exception是的实例Exception,请查看文档以获取有关您可以使用此对象执行的操作(例如访问回溯)的信息。