代码之家  ›  专栏  ›  技术社区  ›  Chris Bunch

在Ruby中自动记录异常

  •  6
  • Chris Bunch  · 技术社区  · 17 年前

    是否有一个库或简单的方法来捕获Ruby程序中抛出的异常并将其记录到文件中?我已经看过了 log4r logger ,但这两个网站上的文档都没有提供任何关于我将如何做到这一点的示例。我远程运行这个程序,如果这些信息有帮助的话,就会丢失对stdout和stderr的句柄。

    你推荐什么?

    5 回复  |  直到 17 年前
        1
  •  14
  •   fny    13 年前

    如果您想在野外散步,请尝试以下方法:

    class Exception
      alias real_init initialize
      def initialize(*args)
        real_init *args
        # log the error (self) or its args here
      end
    end
    

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

        2
  •  5
  •   August Lilleaas    17 年前

    拯救 Exception . 像这样的事情可能是有道理的:

    begin
      # run your code here ..
    rescue Exception => exception
      # logger.error(...) ....
      raise exception
    end
    

    exception 是一个例子 例外 ,看看 the docs

        3
  •  2
  •   John Douthat    17 年前

    如果您正在运行Rails应用程序,则 Exception Notification 插件非常方便。

        4
  •  0
  •   jasim jasim    17 年前

    begin
      main()
    rescue Exception => e
      myCustomErrorLogger(e)
    end
    
    def main()
      # All the application code comes here.
    end
    

    我需要的是将所有未捕获的异常移动到最顶层,并在那里被捕获,然后由错误日志功能记录。

    我现在正在尝试,但如果能得到你的建议,那就太好了。

        5
  •  0
  •   Gareve    15 年前

    不要忘记检查记录器是否可以为null,异常可以在记录器创建之前(或创建时)抛出。

    推荐文章