Module: NewRelic::Agent

Extended by:
Agent
Included in:
Agent
Defined in:
lib/new_relic/agent.rb,
lib/new_relic/agent/agent.rb,
lib/new_relic/agent/sampler.rb,
lib/new_relic/agent/database.rb,
lib/new_relic/agent/shim_agent.rb,
lib/new_relic/agent/sql_sampler.rb,
lib/new_relic/agent/worker_loop.rb,
lib/new_relic/agent/stats_engine.rb,
lib/new_relic/agent/method_tracer.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/transaction_info.rb,
lib/new_relic/agent/browser_monitoring.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/samplers/cpu_sampler.rb,
lib/new_relic/agent/stats_engine/samplers.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/instrumentation/memcache.rb,
lib/new_relic/agent/stats_engine/gc_profiler.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/instrumentation/data_mapper.rb,
lib/new_relic/agent/instrumentation/metric_frame.rb,
lib/new_relic/agent/instrumentation/active_record.rb,
lib/new_relic/agent/instrumentation/rails3/errors.rb,
lib/new_relic/agent/instrumentation/metric_frame/pop.rb,
lib/new_relic/agent/samplers/delayed_job_lock_sampler.rb,
lib/new_relic/agent/instrumentation/rails3/action_controller.rb,
lib/new_relic/agent/instrumentation/controller_instrumentation.rb

Overview

Ruby Agent APIs

This module contains the public API methods for the Ruby Agent.

For adding custom instrumentation to method invocations, refer to the docs in the class NewRelic::Agent::MethodTracer.

For information on how to customize the controller instrumentation, or to instrument something other than Rails so that high level dispatcher actions or background tasks show up as first class operations in New Relic, refer to NewRelic::Agent::Instrumentation::ControllerInstrumentation and NewRelic::Agent::Instrumentation::ControllerInstrumentation::ClassMethods.

Methods in this module as well as documented methods in NewRelic::Agent::MethodTracer and NewRelic::Agent::Instrumentation::ControllerInstrumentation are available to applications. When the agent is not enabled the method implementations are stubbed into no-ops to reduce overhead.

Methods and classes in other parts of the agent are not guaranteed to be available between releases.

Refer to the online docs at support.newrelic.com to see how to access the data collected by custom instrumentation, or e-mail support at New Relic for help.

Defined Under Namespace

Modules: BrowserMonitoring, BusyCalculator, Database, Instrumentation, MethodTracer, Samplers Classes: Agent, BackgroundLoadingError, BeaconConfiguration, ErrorCollector, ForceDisconnectException, ForceRestartException, LicenseException, PostTooBigException, Sampler, ServerConnectionException, ServerError, ShimAgent, SlowSql, SqlSampler, SqlTrace, StatsEngine, TransactionInfo, TransactionSampleBuilder, TransactionSampler, TransactionSqlData, WorkerLoop

Instance Method Summary collapse

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.



321
322
323
# File 'lib/new_relic/agent.rb', line 321

def abort_transaction!
  NewRelic::Agent::Instrumentation::MetricFrame.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.



388
389
390
# File 'lib/new_relic/agent.rb', line 388

def add_custom_parameters(params)
  NewRelic::Agent::Instrumentation::MetricFrame.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.



266
267
268
# File 'lib/new_relic/agent.rb', line 266

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 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.



206
207
208
# File 'lib/new_relic/agent.rb', line 206

def after_fork(options={})
  agent.after_fork(options)
end

#agentObject Also known as: instance

The singleton Agent instance. Used internally.



126
127
128
129
# File 'lib/new_relic/agent.rb', line 126

def agent #:nodoc:
  raise "Plugin not initialized!" if @agent.nil?
  @agent
end

#agent=(new_instance) ⇒ Object

:nodoc:



131
132
133
# File 'lib/new_relic/agent.rb', line 131

def agent=(new_instance)#:nodoc:
  @agent = new_instance
end

Returns a Javascript string which should be injected into the very bottom of the response body



463
464
465
# File 'lib/new_relic/agent.rb', line 463

def browser_timing_footer
  agent.browser_timing_footer
end

#browser_timing_headerObject

Returns a Javascript string which should be injected into the very top of the response body



457
458
459
# File 'lib/new_relic/agent.rb', line 457

def browser_timing_header
  agent.browser_timing_header
end

#disable_all_tracingObject

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



330
331
332
333
334
335
# File 'lib/new_relic/agent.rb', line 330

def disable_all_tracing
  agent.push_trace_execution_flag(false)
  yield
ensure
  agent.pop_trace_execution_flag
end

#disable_sql_recordingObject

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


298
299
300
301
302
303
304
305
# File 'lib/new_relic/agent.rb', line 298

def disable_sql_recording
  state = agent.set_record_sql(false)
  begin
    yield
  ensure
    agent.set_record_sql(state)
  end
end

#disable_transaction_tracingObject

This method disables the recording of transaction traces in the given block. See also #disable_all_tracing



309
310
311
312
313
314
315
316
# File 'lib/new_relic/agent.rb', line 309

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::Stats that accepts data via calls to add_data_point(value).



145
146
147
# File 'lib/new_relic/agent.rb', line 145

def get_stats(metric_name, use_scope=false)
  agent.stats_engine.get_stats(metric_name, use_scope)
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.



363
364
365
# File 'lib/new_relic/agent.rb', line 363

def ignore_error_filter(&block)
  agent.error_collector.ignore_error_filter(&block)
end

#is_execution_traced?Boolean

Check to see if we are capturing metrics currently on this thread.

Returns:

  • (Boolean)


338
339
340
# File 'lib/new_relic/agent.rb', line 338

def is_execution_traced?
  Thread.current[:newrelic_untraced].nil? || Thread.current[:newrelic_untraced].last != false
end

#is_sql_recorded?Boolean

helper method to check the thread local to determine whether sql is being recorded or not

Returns:

  • (Boolean)


350
351
352
# File 'lib/new_relic/agent.rb', line 350

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

Returns:

  • (Boolean)


344
345
346
# File 'lib/new_relic/agent.rb', line 344

def is_transaction_traced?
  Thread::current[:record_tt] != false
end

#load_dataObject

Note that only one transaction trace will be sent even if many are serialized, since the slowest is sent.

See also the complement to this method, #save_data - used when a process is shutting down



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/new_relic/agent.rb', line 244

def load_data
  if !NewRelic::Control.instance['disable_serialization']
    NewRelic::DataSerialization.read_and_write_to_file do |old_data|
      agent.merge_data_from(old_data)
      nil # return nil so nothing is written to the file
    end
    NewRelic::DataSerialization.update_last_sent!
  end
  
  {
    :metrics => agent.stats_engine.metrics.length,
    :traces => agent.unsent_traces_size,
    :errors => agent.unsent_errors_size
  }
end

#loggerObject

Get the logger for the agent. Available after the agent has initialized. This sends output to the agent log file. If the agent has not initialized a standard output logger is returned.



154
155
156
157
158
159
160
161
162
# File 'lib/new_relic/agent.rb', line 154

def logger
  control = NewRelic::Control.instance(false)
  if control
    control.log
  else
    require 'logger'
    @stdoutlog ||= Logger.new $stdout
  end
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.



179
180
181
182
# File 'lib/new_relic/agent.rb', line 179

def manual_start(options={})
  raise "Options must be a hash" unless Hash === options
  NewRelic::Control.instance.init_plugin({ :agent_enabled => true, :sync_startup => true }.merge(options))
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.



381
382
383
# File 'lib/new_relic/agent.rb', line 381

def notice_error(exception, options={})
  NewRelic::Agent::Instrumentation::MetricFrame.notice_error(exception, options)
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 like OtherTransaction/Background/Class/method. Ignored if uri 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



451
452
453
# File 'lib/new_relic/agent.rb', line 451

def record_transaction(response_sec, options = {})
  agent.record_transaction(response_sec, options)
end

#reset_statsObject

Clear out any unsent metric data. See NewRelic::Agent::Agent#reset_stats



211
212
213
# File 'lib/new_relic/agent.rb', line 211

def reset_stats
  agent.reset_stats
end

#save_dataObject

a method used to serialize short-running processes to disk, so we don’t incur the overhead of reporting to the server for every fork/invocation of a small job.

Functionally, this loads the data from the file into the agent (to avoid losing data by overwriting) and then serializes the agent data to the file again. See also #load_data



228
229
230
231
232
233
# File 'lib/new_relic/agent.rb', line 228

def save_data
  NewRelic::DataSerialization.read_and_write_to_file do |old_data|
    agent.merge_data_from(old_data)
    agent.serialize
  end
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


284
285
286
# File 'lib/new_relic/agent.rb', line 284

def set_sql_obfuscator(type = :replace, &block)
  NewRelic::Agent::Database.set_sql_obfuscator(type, &block)
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



401
402
403
# File 'lib/new_relic/agent.rb', line 401

def set_user_attributes(attributes)
  NewRelic::Agent::Instrumentation::MetricFrame.set_user_attributes(attributes)
end

#shutdown(options = {}) ⇒ Object

Shutdown the agent. Call this before exiting. Sends any queued data and kills the background thread.



217
218
219
# File 'lib/new_relic/agent.rb', line 217

def shutdown(options={})
  agent.shutdown(options)
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.



417
418
419
420
421
422
423
# File 'lib/new_relic/agent.rb', line 417

def with_database_metric_name(model, method, &block)
  if frame = NewRelic::Agent::Instrumentation::MetricFrame.current
    frame.with_database_metric_name(model, method, &block)
  else
    yield
  end
end