rake任务中的Railsexception通知程序
我有一个简单的rails应用程序,带有一些控制器和一些rake任务。 由gem配置的cron执行几个任务。
我的任务之一是每天执行,有时会引发exception,默认情况下我会收到cron的警告
rake aborted! undefined method `parameterize' for nil:NilClass Tasks: TOP => mailboxes:clean_processed (See full trace by running task with --trace)
我想调试正在发生的事情,因此我刚刚在我的Gemfile
使用此行安装了此exception通知 gem
gem "exception_notification", "~> 2.4.1", :require => 'exception_notifier'
并在我的application.rb
文件中配置它
# enable exception notification config.middleware.use ExceptionNotifier, :email_prefix => "[MyAppName] ", :sender_address => %{"notifier" }, :exception_recipients => %w{me@example.com}
由于这个gem是一个机架中间件,它只适用于Web请求而不适用于rake任务。 我也想为rake任务启用它,我找到了这个工作的要点 。
它工作,但它不是DRY,我需要在该方法中重复gem配置,我还需要更改所有我的rake任务,将它们的语句括在一个块中,如同
exception_notify { actual_task_code }
有没有更好的方法来解决这个问题?
PS如果我需要更改通知gem不会有问题,因为我只为我的项目添加了几行代码。
PPS我知道我也可以改变crontab中的rake行来添加一个--trace
选项,但是我不喜欢那个解决方案,导致exception通知程序imho是一个更好的解决方案,它也有助于Web代码。
更新我刚刚发现了这个相关的问题: delayed_not的exceptions_notification,但两个答案都使用了类似的技巧。
我将尝试像Airbrake(以前称为hoptoad)或Exceptional这样的在线服务,但它们都是付费服务……
更新2 :我尝试了Airbrake App ,非常好的应用程序,但它遇到同样的问题,我仍然需要破解Rakefile来通知rake任务的exception。 然而,hack不那么干,因为你只需要这个代码:
# notify exceptions def exception_notify yield rescue Exception => exception HoptoadNotifier.notify exception raise exception end
无需重复任何配置参数。 我想我不能做得比这更好,以获得rake任务中的exception通知。
在config / initializers中创建一个task.rb文件,其中有猴子补丁Rake :: Task#execute包含exception_notify的function:
module Rake class Task alias :orig_execute :execute def execute(args=nil) orig_execute(args) rescue Exception => exception # Exception notification stuff end end end
使用Rails 3.0.12,Rake 0.9.2.2进行测试。
有一个新的更简单的解决方案:gem https://github.com/nikhaldi/exception_notification-rake
Airbrakegem贴片Rake允许救援,所以它已经做了我要求的…
谢谢你的建议; 它对我很有用,因为我现在只有一个cron任务。
要干它,您可以将配置转换为常量,可能通过APP_CONFIG
: https : //github.com/cjbottaro/app_config
另外,你可以扩展任何类来处理task :... do
以在exception_notify { }
包装所有内容。