在整个Rails 4应用程序中记录自定义New Relic属性的正确方法

Gre*_*ley 0 ruby-on-rails newrelic

我正在使用New Relic监视我的Rails 4.2应用程序,并且运行良好。

但是,当New Relic向我报告一个用户时,我希望能够知道哪个用户遇到了错误。

我已经读过这篇文章,我相信可以解释如何在每个控制器的基础上添加自定义属性。

但是,就我而言,我想记录current_user.id整个应用程序的自定义属性。

我首先想到的是将以下内容放入applications_controller.rb

class ApplicationController < ActionController::Base

  ::NewRelic::Agent.add_custom_parameters(
    :user_name => current_user.full_name rescue "Not a logged-in user.",
    :user_id => current_user.id rescue "Not a logged-in user."
  )
Run Code Online (Sandbox Code Playgroud)

...但这导致服务器错误。

有什么建议么?

更新/解决方案

我在上面所做的事情有两个问题。首先,我使用rescue不当。其次,我需要创建一个方法添加这些自定义属性调用该方法在ApplicationController使用之前的一切before_filter。这是最终为我工作的示例:

class ApplicationController < ActionController::Base

  # attempt to gather user and organization attributes before all controller actions for New Relic error logging
  before_filter :record_new_relic_custom_attributes

  def record_new_relic_custom_attributes
    # record some custom attributes for New Relic
    new_relic_user_id = current_user.id rescue "Not a logged-in user."
    new_relic_user_name = current_user.full_name rescue "Not a logged-in user."
    new_relic_user_email = current_user.email rescue "Not a logged-in user."
    new_relic_organization_id = current_organization.id rescue "Not a logged-in user."
    new_relic_organization_name = current_organization.name rescue "Not a logged-in user."
    new_relic_organization_email = current_organization.email rescue "Not a logged-in user."
    ::NewRelic::Agent.add_custom_parameters(
      :user_id => new_relic_user_id,
      :user_name => new_relic_user_name,
      :user_email => new_relic_user_email,
      :organization_id => new_relic_organization_id,
      :organization_name => new_relic_organization_name,
      :organization_email => new_relic_organization_email
    )
  end
Run Code Online (Sandbox Code Playgroud)

更新2 根据下面的评论者之一,rescue在这种情况下使用不是理想的,我应该使用try

new_relic_user_id = current_user.try(:id) || "Not a logged-in user."
Run Code Online (Sandbox Code Playgroud)

Nic*_*ick 5

您可能希望将该代码包含在过滤器中,以使其在控制器操作之前运行,例如:

class ApplicationController < ActionController::Base
  before_filter :set_new_relic_user

  def set_new_relic_user
    ::NewRelic::Agent.add_custom_parameters(
      :user_name => current_user.full_name rescue "Not a logged-in user.",
      :user_id => current_user.id rescue "Not a logged-in user."
    )                                                
  end
end                                                  
Run Code Online (Sandbox Code Playgroud)

  • 甚至`current_user.try(:full_name)|| “不是登录用户。”在这里会更好。 (2认同)