Module: NewRelic::Agent
- Extended by:
- Forwardable, Agent, Configuration::Instance
- Included in:
- Agent
- Defined in:
- lib/new_relic/agent.rb,
lib/new_relic/agent/agent.rb,
lib/new_relic/agent/stats.rb,
lib/new_relic/agent/thread.rb,
lib/new_relic/agent/sampler.rb,
lib/new_relic/agent/database.rb,
lib/new_relic/agent/autostart.rb,
lib/new_relic/agent/shim_agent.rb,
lib/new_relic/agent/null_logger.rb,
lib/new_relic/agent/sql_sampler.rb,
lib/new_relic/agent/system_info.rb,
lib/new_relic/agent/transaction.rb,
lib/new_relic/agent/worker_loop.rb,
lib/new_relic/agent/agent_logger.rb,
lib/new_relic/agent/audit_logger.rb,
lib/new_relic/agent/pipe_service.rb,
lib/new_relic/agent/rules_engine.rb,
lib/new_relic/agent/stats_engine.rb,
lib/new_relic/agent/configuration.rb,
lib/new_relic/agent/method_tracer.rb,
lib/new_relic/agent/event_listener.rb,
lib/new_relic/agent/busy_calculator.rb,
lib/new_relic/agent/error_collector.rb,
lib/new_relic/agent/instrumentation.rb,
lib/new_relic/agent/thread_profiler.rb,
lib/new_relic/agent/transaction/pop.rb,
lib/new_relic/agent/transaction_info.rb,
lib/new_relic/agent/cross_app_monitor.rb,
lib/new_relic/agent/cross_app_tracing.rb,
lib/new_relic/agent/new_relic_service.rb,
lib/new_relic/agent/browser_monitoring.rb,
lib/new_relic/agent/sampler_collection.rb,
lib/new_relic/agent/transaction_sampler.rb,
lib/new_relic/agent/beacon_configuration.rb,
lib/new_relic/agent/instrumentation/rack.rb,
lib/new_relic/agent/pipe_channel_manager.rb,
lib/new_relic/agent/samplers/cpu_sampler.rb,
lib/new_relic/agent/configuration/manager.rb,
lib/new_relic/agent/http_clients/uri_util.rb,
lib/new_relic/agent/stats_engine/samplers.rb,
lib/new_relic/agent/configuration/defaults.rb,
lib/new_relic/agent/instrumentation/sinatra.rb,
lib/new_relic/agent/samplers/memory_sampler.rb,
lib/new_relic/agent/samplers/object_sampler.rb,
lib/new_relic/agent/stats_engine/stats_hash.rb,
lib/new_relic/agent/instrumentation/memcache.rb,
lib/new_relic/agent/stats_engine/gc_profiler.rb,
lib/new_relic/agent/configuration/yaml_source.rb,
lib/new_relic/agent/stats_engine/metric_stats.rb,
lib/new_relic/agent/stats_engine/transactions.rb,
lib/new_relic/agent/instrumentation/queue_time.rb,
lib/new_relic/agent/transaction_sample_builder.rb,
lib/new_relic/agent/configuration/mask_defaults.rb,
lib/new_relic/agent/configuration/server_source.rb,
lib/new_relic/agent/http_clients/excon_wrappers.rb,
lib/new_relic/agent/instrumentation/data_mapper.rb,
lib/new_relic/agent/instrumentation/metric_frame.rb,
lib/new_relic/agent/samplers/delayed_job_sampler.rb,
lib/new_relic/agent/instrumentation/active_record.rb,
lib/new_relic/agent/instrumentation/rails3/errors.rb,
lib/new_relic/agent/instrumentation/rails4/errors.rb,
lib/new_relic/agent/http_clients/net_http_wrappers.rb,
lib/new_relic/agent/http_clients/typhoeus_wrappers.rb,
lib/new_relic/agent/instrumentation/sinatra/ignorer.rb,
lib/new_relic/agent/configuration/environment_source.rb,
lib/new_relic/agent/instrumentation/evented_subscriber.rb,
lib/new_relic/agent/instrumentation/active_record_helper.rb,
lib/new_relic/agent/instrumentation/action_view_subscriber.rb,
lib/new_relic/agent/instrumentation/active_record_subscriber.rb,
lib/new_relic/agent/instrumentation/rails3/action_controller.rb,
lib/new_relic/agent/instrumentation/rails4/action_controller.rb,
lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb,
lib/new_relic/agent/instrumentation/browser_monitoring_timings.rb,
lib/new_relic/agent/instrumentation/controller_instrumentation.rb,
lib/new_relic/agent/instrumentation/action_controller_subscriber.rb
Overview
This file is distributed under New Relic’s license terms. See github.com/newrelic/rpm/blob/master/LICENSE for complete details.
Defined Under Namespace
Modules: Autostart, BrowserMonitoring, BusyCalculator, Configuration, CrossAppTracing, Database, HTTPClients, Instrumentation, MethodTracer, PipeChannelManager, Samplers, SystemInfo Classes: Agent, AgentLogger, AgentThread, AuditLogger, BackgroundLoadingError, BeaconConfiguration, ChainedStats, CrossAppMonitor, ErrorCollector, EventListener, ForceDisconnectException, ForceRestartException, LicenseException, MemoryLogger, NewRelicService, NullLogger, PipeService, RequestSampler, RulesEngine, Sampler, SamplerCollection, ServerConnectionException, ServerError, ShimAgent, SlowSql, SqlSampler, SqlTrace, StartupLogger, Stats, StatsEngine, StatsHash, ThreadProfile, ThreadProfiler, Transaction, TransactionInfo, TransactionSampleBuilder, TransactionSampler, TransactionSqlData, UnrecoverableAgentException, UnrecoverableServerException, WorkerLoop
Constant Summary collapse
- UNKNOWN_METRIC =
placeholder name used when we cannot determine a transaction’s name
'(unknown)'.freeze
Instance Method Summary collapse
-
#abort_transaction! ⇒ Object
Cancel the collection of the current transaction in progress, if any.
-
#add_custom_parameters(params) ⇒ Object
(also: #add_request_parameters)
Add parameters to the current transaction trace (and traced error if any) on the call stack.
-
#add_instrumentation(file_pattern) ⇒ Object
Add instrumentation files to the agent.
-
#after_fork(options = {}) ⇒ Object
Register this method as a callback for processes that fork jobs.
-
#agent ⇒ Object
(also: #instance)
The singleton Agent instance.
-
#agent=(new_instance) ⇒ Object
:nodoc:.
-
#browser_timing_footer ⇒ Object
Returns a Javascript string which should be injected into the very bottom of the response body.
-
#browser_timing_header ⇒ Object
Returns a Javascript string which should be injected into the very top of the response body.
-
#disable_all_tracing ⇒ Object
Yield to the block without collecting any metrics or traces in any of the subsequent calls.
-
#disable_sql_recording ⇒ Object
This method sets the state of sql recording in the transaction sampler feature.
-
#disable_transaction_tracing ⇒ Object
This method disables the recording of transaction traces in the given block.
- #get_stats(metric_name, use_scope = false) ⇒ Object (also: #get_stats_no_scope) deprecated Deprecated.
-
#get_transaction_name ⇒ Object
Get the name of the current running transaction.
-
#ignore_error_filter(&block) ⇒ Object
Set a filter to be applied to errors that the Ruby Agent will track.
-
#increment_metric(metric_name, amount = 1) ⇒ Object
Increment a simple counter metric.
-
#is_execution_traced? ⇒ Boolean
Check to see if we are capturing metrics currently on this thread.
-
#is_sql_recorded? ⇒ Boolean
helper method to check the thread local to determine whether sql is being recorded or not.
-
#is_transaction_traced? ⇒ Boolean
helper method to check the thread local to determine whether the transaction in progress is traced or not.
-
#logger ⇒ Object
Primary interface to logging is fronted by this accessor Access via ::NewRelic::Agent.logger.
- #logger=(log) ⇒ Object
-
#manual_start(options = {}) ⇒ Object
Call this to manually start the Agent in situations where the Agent does not auto-start.
-
#notice_error(exception, options = {}) ⇒ Object
Record the given error.
-
#notify(event_type, *args) ⇒ Object
Fire an event of the specified
event_type
, passing it an the givenargs
to any registered handlers. -
#record_metric(metric_name, value) ⇒ Object
Record a value for the given metric name.
-
#record_transaction(response_sec, options = {}) ⇒ Object
Record a web transaction from an external source.
-
#reset_stats ⇒ Object
Clear out any unsent metric data.
-
#set_sql_obfuscator(type = :replace, &block) ⇒ Object
This method sets the block sent to this method as a sql obfuscator.
-
#set_transaction_name(name, options = {}) ⇒ Object
Set the name of the current running transaction.
-
#set_user_attributes(attributes) ⇒ Object
Set attributes about the user making this request.
-
#shutdown(options = {}) ⇒ Object
Shutdown the agent.
-
#subscribe(event_type, &handler) ⇒ Object
Subscribe to events of
event_type
, calling the givenhandler
when one is sent. -
#with_database_metric_name(model, method, &block) ⇒ Object
Yield to a block that is run with a database metric name context.
Methods included from Configuration::Instance
Instance Method Details
#abort_transaction! ⇒ Object
Cancel the collection of the current transaction in progress, if any. Only affects the transaction started on this thread once it has started and before it has completed.
369 370 371 |
# File 'lib/new_relic/agent.rb', line 369 def abort_transaction! Transaction.abort_transaction! end |
#add_custom_parameters(params) ⇒ Object Also known as: add_request_parameters
Add parameters to the current transaction trace (and traced error if any) on the call stack.
438 439 440 |
# File 'lib/new_relic/agent.rb', line 438 def add_custom_parameters(params) Transaction.add_custom_parameters(params) end |
#add_instrumentation(file_pattern) ⇒ Object
Add instrumentation files to the agent. The argument should be a glob matching ruby scripts which will be executed at the time instrumentation is loaded. Since instrumentation is not loaded when the agent is not running it’s better to use this method to register instrumentation than just loading the files directly, although that probably also works.
297 298 299 |
# File 'lib/new_relic/agent.rb', line 297 def add_instrumentation(file_pattern) NewRelic::Control.instance.add_instrumentation file_pattern end |
#after_fork(options = {}) ⇒ Object
Register this method as a callback for processes that fork jobs.
If the master/parent connects to the agent prior to forking the agent in the forked process will use that agent_run. Otherwise the forked process will establish a new connection with the server.
Use this especially when you fork the process to run background jobs or other work. If you are doing this with a web dispatcher that forks worker processes then you will need to force the agent to reconnect, which it won’t do by default. Passenger and Rainbows and Unicorn are already handled, nothing special needed for them.
Options:
-
:force_reconnect => true
to force the spawned process to establish a new connection, such as when forking a long running process. The default is false–it will only connect to the server if the parent had not connected. -
:keep_retrying => false
if we try to initiate a new connection, this tells me to only try it once so this method returns quickly if there is some kind of latency with the server.
276 277 278 |
# File 'lib/new_relic/agent.rb', line 276 def after_fork(={}) agent.after_fork() end |
#agent ⇒ Object Also known as: instance
The singleton Agent instance. Used internally.
150 151 152 |
# File 'lib/new_relic/agent.rb', line 150 def agent #:nodoc: @agent || raise("Plugin not initialized!") end |
#agent=(new_instance) ⇒ Object
:nodoc:
154 155 156 |
# File 'lib/new_relic/agent.rb', line 154 def agent=(new_instance)#:nodoc: @agent = new_instance end |
#browser_timing_footer ⇒ Object
Returns a Javascript string which should be injected into the very bottom of the response body
554 555 556 |
# File 'lib/new_relic/agent.rb', line 554 def agent. end |
#browser_timing_header ⇒ Object
Returns a Javascript string which should be injected into the very top of the response body
548 549 550 |
# File 'lib/new_relic/agent.rb', line 548 def browser_timing_header agent.browser_timing_header end |
#disable_all_tracing ⇒ Object
Yield to the block without collecting any metrics or traces in any of the subsequent calls. If executed recursively, will keep track of the first entry point and turn on tracing again after leaving that block. This uses the thread local newrelic_untrace
378 379 380 381 382 383 |
# File 'lib/new_relic/agent.rb', line 378 def disable_all_tracing agent.push_trace_execution_flag(false) yield ensure agent.pop_trace_execution_flag end |
#disable_sql_recording ⇒ Object
This method sets the state of sql recording in the transaction sampler feature. Within the given block, no sql will be recorded
usage:
NewRelic::Agent.disable_sql_recording do
...
end
329 330 331 332 333 334 335 336 |
# File 'lib/new_relic/agent.rb', line 329 def disable_sql_recording state = agent.set_record_sql(false) begin yield ensure agent.set_record_sql(state) end end |
#disable_transaction_tracing ⇒ Object
This method disables the recording of transaction traces in the given block. See also #disable_all_tracing
357 358 359 360 361 362 363 364 |
# File 'lib/new_relic/agent.rb', line 357 def disable_transaction_tracing state = agent.set_record_tt(false) begin yield ensure agent.set_record_tt(state) end end |
#get_stats(metric_name, use_scope = false) ⇒ Object Also known as: get_stats_no_scope
Get or create a statistics gatherer that will aggregate numerical data under a metric name.
metric_name
should follow a slash separated path convention. Application specific metrics should begin with “Custom/”.
Return a NewRelic::Agent::Stats that accepts data via calls to add_data_point(value).
225 226 227 |
# File 'lib/new_relic/agent.rb', line 225 def get_stats(metric_name, use_scope=false) agent.stats_engine.get_stats(metric_name, use_scope) end |
#get_transaction_name ⇒ Object
Get the name of the current running transaction. This is useful if you want to modify the default name.
489 490 491 492 493 494 |
# File 'lib/new_relic/agent.rb', line 489 def get_transaction_name if Transaction.current namer = Instrumentation::ControllerInstrumentation::TransactionNamer.new(self) Transaction.current.name.sub(Regexp.new("\\A#{Regexp.escape(namer.category_name)}/"), '') end end |
#ignore_error_filter(&block) ⇒ Object
Set a filter to be applied to errors that the Ruby Agent will track. The block should evalute to the exception to track (which could be different from the original exception) or nil to ignore this exception.
The block is yielded to with the exception to filter.
Return the new block or the existing filter Proc if no block is passed.
412 413 414 |
# File 'lib/new_relic/agent.rb', line 412 def ignore_error_filter(&block) agent.error_collector.ignore_error_filter(&block) end |
#increment_metric(metric_name, amount = 1) ⇒ Object
Increment a simple counter metric.
metric_name
should follow a slash separated path convention. Application specific metrics should begin with “Custom/”.
This method is safe to use from any thread.
209 210 211 212 213 |
# File 'lib/new_relic/agent.rb', line 209 def increment_metric(metric_name, amount=1) agent.stats_engine.record_metrics(metric_name) do |stats| stats.increment_count(amount) end end |
#is_execution_traced? ⇒ Boolean
Check to see if we are capturing metrics currently on this thread.
386 387 388 389 |
# File 'lib/new_relic/agent.rb', line 386 def is_execution_traced? untraced = Thread.current[:newrelic_untraced] untraced.nil? || untraced.last != false end |
#is_sql_recorded? ⇒ Boolean
helper method to check the thread local to determine whether sql is being recorded or not
399 400 401 |
# File 'lib/new_relic/agent.rb', line 399 def is_sql_recorded? Thread::current[:record_sql] != false end |
#is_transaction_traced? ⇒ Boolean
helper method to check the thread local to determine whether the transaction in progress is traced or not
393 394 395 |
# File 'lib/new_relic/agent.rb', line 393 def is_transaction_traced? Thread::current[:record_tt] != false end |
#logger ⇒ Object
Primary interface to logging is fronted by this accessor Access via ::NewRelic::Agent.logger
162 163 164 |
# File 'lib/new_relic/agent.rb', line 162 def logger @logger || StartupLogger.instance end |
#logger=(log) ⇒ Object
166 167 168 |
# File 'lib/new_relic/agent.rb', line 166 def logger=(log) @logger = log end |
#manual_start(options = {}) ⇒ Object
Call this to manually start the Agent in situations where the Agent does not auto-start.
When the app environment loads, so does the Agent. However, the Agent will only connect to the service if a web front-end is found. If you want to selectively monitor ruby processes that don’t use web plugins, then call this method in your code and the Agent will fire up and start reporting to the service.
Options are passed in as overrides for values in the newrelic.yml, such as app_name. In addition, the option log
will take a logger that will be used instead of the standard file logger. The setting for the newrelic.yml section to use (ie, RAILS_ENV) can be overridden with an :env argument.
246 247 248 249 250 251 252 |
# File 'lib/new_relic/agent.rb', line 246 def manual_start(={}) raise "Options must be a hash" unless Hash === if [:start_channel_listener] NewRelic::Agent::PipeChannelManager.listener.start end NewRelic::Control.instance.init_plugin({ :agent_enabled => true, :sync_startup => true }.merge()) end |
#notice_error(exception, options = {}) ⇒ Object
Record the given error. It will be passed through the #ignore_error_filter if there is one.
-
exception
is the exception which will be recorded. May also be an error message.
Options:
-
:uri
=> The request path, minus any request params or query string. -
:referer
=> The URI of the referer -
:metric
=> The metric name associated with the transaction -
:request_params
=> Request parameters, already filtered if necessary -
:custom_params
=> Custom parameters
Anything left over is treated as custom params.
430 431 432 433 |
# File 'lib/new_relic/agent.rb', line 430 def notice_error(exception, ={}) Transaction.notice_error(exception, ) nil # don't return a noticed error datastructure. it can only hurt. end |
#notify(event_type, *args) ⇒ Object
Fire an event of the specified event_type
, passing it an the given args
to any registered handlers.
348 349 350 351 352 |
# File 'lib/new_relic/agent.rb', line 348 def notify(event_type, *args) agent.events.notify( event_type, *args ) rescue => err NewRelic::Agent.logger.debug "Ignoring exception during %p event notification" % [event_type] end |
#record_metric(metric_name, value) ⇒ Object
Record a value for the given metric name.
This method should be used to record event-based metrics such as method calls that are associated with a specific duration or magnitude.
metric_name
should follow a slash separated path convention. Application specific metrics should begin with “Custom/”.
value
should be either a single Numeric value representing the duration/ magnitude of the event being recorded, or a Hash containing :count, :total, :min, :max, and :sum_of_squares keys. The latter form is useful for recording pre-aggregated metrics collected externally.
This method is safe to use from any thread.
186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/new_relic/agent.rb', line 186 def record_metric(metric_name, value) if value.is_a?(Hash) stats = NewRelic::Agent::Stats.new stats.call_count = value[:count] if value[:count] stats.total_call_time = value[:total] if value[:total] stats.total_exclusive_time = value[:total] if value[:total] stats.min_call_time = value[:min] if value[:min] stats.max_call_time = value[:max] if value[:max] stats.sum_of_squares = value[:sum_of_squares] if value[:sum_of_squares] value = stats end agent.stats_engine.record_metrics(metric_name, value) end |
#record_transaction(response_sec, options = {}) ⇒ Object
Record a web transaction from an external source. This will process the response time, error, and score an apdex value.
First argument is a float value, time in seconds. Option keys are strings.
Identifying the transaction
-
'uri' => uri
to record the value for a given web request. If not provided, just record the aggregate dispatcher and apdex scores. -
'metric' => metric_name
to record with a general metric name likeOtherTransaction/Background/Class/method
. Ignored ifuri
is provided.
Error options
Provide one of the following:
-
'is_error' => true
if an unknown error occurred -
'error_message' => msg
if an error message is available -
'exception' => exception
if a ruby exception is recorded
Misc options
Additional information captured in errors
-
'referer' => referer_url
-
'request_params' => hash
to record a set of name/value pairs as the request parameters. -
'custom_params' => hash
to record extra information in traced errors
542 543 544 |
# File 'lib/new_relic/agent.rb', line 542 def record_transaction(response_sec, = {}) agent.record_transaction(response_sec, ) end |
#reset_stats ⇒ Object
Clear out any unsent metric data. See NewRelic::Agent::Agent#reset_stats
281 282 283 |
# File 'lib/new_relic/agent.rb', line 281 def reset_stats agent.reset_stats end |
#set_sql_obfuscator(type = :replace, &block) ⇒ Object
This method sets the block sent to this method as a sql obfuscator. The block will be called with a single String SQL statement to obfuscate. The method must return the obfuscated String SQL. If chaining of obfuscators is required, use type = :before or :after
type = :before, :replace, :after
Example:
NewRelic::Agent.set_sql_obfuscator(:replace) do |sql|
my_obfuscator(sql)
end
315 316 317 |
# File 'lib/new_relic/agent.rb', line 315 def set_sql_obfuscator(type = :replace, &block) NewRelic::Agent::Database.set_sql_obfuscator(type, &block) end |
#set_transaction_name(name, options = {}) ⇒ Object
Set the name of the current running transaction. The agent will apply a reasonable default based on framework routing, but in cases where this is insufficient, this can be used to manually control the name of the transaction. The category of transaction can be specified via the :category
option:
-
:category => :controller
indicates that this is a controller action and will appear with all the other actions. -
:category => :task
indicates that this is a background task and will show up in New Relic with other background tasks instead of in the controllers list -
:category => :rack
if you are instrumenting a rack middleware call. The:name
is optional, useful if you have more than one potential transaction in the #call. -
:category => :uri
indicates that this is a web transaction whose name is a normalized URI, where ‘normalized’ means the URI does not have any elements with data in them such as in many REST URIs.
The default category is the same as the running transaction.
477 478 479 480 481 482 483 |
# File 'lib/new_relic/agent.rb', line 477 def set_transaction_name(name, ={}) if Transaction.current namer = Instrumentation::ControllerInstrumentation::TransactionNamer.new(self) Transaction.current.type = [:category] if [:category] Transaction.current.name = "#{namer.category_name([:category])}/#{name}" end end |
#set_user_attributes(attributes) ⇒ Object
Set attributes about the user making this request. These attributes will be automatically appended to any Transaction Trace or Error that is collected. These attributes will also be collected for RUM requests.
Attributes (hash)
-
:user
=> user name or ID -
:account
=> account name or ID -
:product
=> product name or level
451 452 453 |
# File 'lib/new_relic/agent.rb', line 451 def set_user_attributes(attributes) Transaction.set_user_attributes(attributes) end |
#shutdown(options = {}) ⇒ Object
Shutdown the agent. Call this before exiting. Sends any queued data and kills the background thread.
287 288 289 |
# File 'lib/new_relic/agent.rb', line 287 def shutdown(={}) agent.shutdown() end |
#subscribe(event_type, &handler) ⇒ Object
Subscribe to events of event_type
, calling the given handler
when one is sent.
341 342 343 |
# File 'lib/new_relic/agent.rb', line 341 def subscribe(event_type, &handler) agent.events.subscribe( event_type, &handler ) end |
#with_database_metric_name(model, method, &block) ⇒ Object
Yield to a block that is run with a database metric name context. This means the Database instrumentation will use this for the metric name if it does not otherwise know about a model. This is re-entrant.
-
model
is the DB model class -
method
is the name of the finder method or other method to identify the operation with.
508 509 510 511 512 513 514 |
# File 'lib/new_relic/agent.rb', line 508 def with_database_metric_name(model, method, &block) if txn = Transaction.current txn.with_database_metric_name(model, method, &block) else yield end end |