我有一个 Rails 操作,其 83% 的运行时间都花在了这个上:
ApplicationCode in (Nested/Controller/my_controller/my_action
有一个信息弹出窗口显示以下内容:
无法使用更深入的可见性,因为这些类和方法未使用 Ruby Agents 当前配置进行检测。请参阅我们的文档,了解如何向您的应用添加自定义指标。
我在这次行动中没有做任何不寻常的事情。有什么想法为什么会这样说吗?是否有一些内部 Rails 代码未被跟踪?
New Relic 代理不是完整的分析器。它能够跟踪它所支持的许多框架和库中可用的一些方法。
通常,当您看到这样的条目(ApplicationCode in (Nested/Controller/my_controller/my_action) 时,这意味着要么是该方法内的代码花费了太长时间(认为是一个长时间运行的循环),要么是您的某些方法代理不会知道。
class MyController < ApplicationController
def my_action
1000.times do
# something that takes time
end
end
def another_action
Foo.new.do_something
end
end
class Foo
def do_something
# something that takes time
end
end
在
my_action
中,您可以使用 Trace API 来跟踪代码块。
require 'new_relic/agent/method_tracer'
class MyController < ApplicationController
extend ::NewRelic::Agent::MethodTracer
def my_action
self.class.trace_execution_scoped(['Custom/slow_action/beginning_work']) do
1000.times do
# something that takes time
end
end
end
end
或者对于您正在调用另一个方法的情况(如
another_action
中),您可以使用方法跟踪器。
require 'new_relic/agent/method_tracer'
class Foo
def do_something
# something that takes time
end
class << self
include ::NewRelic::Agent::MethodTracer
add_method_tracer :do_something, 'Custom/do_something'
end
end