【问题标题】:Rails : How to log all exceptions thrown in rake tasksRails:如何记录 rake 任务中抛出的所有异常
【发布时间】:2020-06-21 16:34:08
【问题描述】:

使用我编写的自定义 ErrorLogger,我试图找到一种方法来记录我的任何 rake 任务中发生的所有错误。一种替代方法是简单地将 begin-rescue 块添加到每个 *.rake 文件中:

# lib/tasks/example.rake
require 'error_logger/error_logger'

namespace :example do
  task generic_example: :environment do
    begin
      ...task code here
    rescue Exception => e
      ErrorLogger.log(e)
      raise e
    end
  end
end

但是对所有任务文件都这样做并不是很干,所以我想知道是否有更聪明的方法。

例如,我将我的控制器错误记录在 application_controller 中,因此无论哪个控制器正在处理请求,它都会运行:

#app/controllers/application_controller.rb
require 'error_logger/error_logger'

class ApplicationController < ActionController::Base
  rescue_from Exception, with: :error_middleware

  def error_middleware(exception)
    ErrorLogger.log(exception)

    raise error
  end
end

在 rake 任务中执行类似操作的最佳方法是什么,只需编写一次日志记录逻辑并将其应用于所有 rake 任务?也许我可以在 Rakefile 中添加一些代码来实现它?

【问题讨论】:

    标签: ruby-on-rails rake


    【解决方案1】:

    您可以通过猴子修补 rake 来完成此任务,如下所示

    module Rake
      class Task
        alias_method :invoke_without_loggable, :invoke
    
        def invoke(*args)
          begin
            invoke_without_loggable(*args)
          rescue StandardError => e
            ErrorLogger.log(e)
            raise e
          end
        end
      end
    end
    

    【讨论】:

    • 嗨,Al-waleed,这很有趣!我从来没有做过猴子补丁,你知道我应该把这段代码放在哪里吗?我是否对“调用”方法或“执行”方法进行猴子修补是否无所谓?
    • 你可以把它放在任何地方,只要它是由 rake 任务(Rakefile)加载的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 2011-11-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多