Module: NewRelic::Agent

Extended by:
Forwardable, Agent
Included in:
Agent
Defined in:
lib/new_relic/agent.rb,
lib/new_relic/agent/method_tracer.rb,
lib/new_relic/agent/instrumentation/controller_instrumentation.rb,
lib/new_relic/agent/instrumentation/rack.rb,
lib/new_relic/agent/datastores.rb,
lib/new_relic/agent/sql_sampler.rb,
lib/new_relic/agent/transaction.rb,
lib/new_relic/agent/transaction_sampler.rb

Overview

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

For adding custom instrumentation to method invocations, see the docs for MethodTracer and MethodTracer::ClassMethods.

For information on how to trace transactions in non-Rack contexts, see Instrumentation::ControllerInstrumentation.

For general documentation about the Ruby agent, see: docs.newrelic.com/docs/agents/ruby-agent

Defined Under Namespace

Modules: Datastores, Instrumentation, MethodTracer Classes: SqlSampler, Transaction, TransactionSampler

Recording custom metrics collapse

Recording custom errors collapse

Recording custom Insights events collapse

Manual agent configuration and startup/shutdown collapse

Ignoring or excluding data collapse

Adding custom attributes to traces collapse

Transaction naming collapse

Manual browser monitoring configuration collapse

Instance Method Details

#add_custom_attributes(params) ⇒ Object

Add attributes to the transaction trace, Insights Transaction event, and any traced errors recorded for the current transaction.

If Browser Monitoring is enabled, and the browser_monitoring.attributes.enabled configuration setting is true, these custom attributes will also be present in the script injected into the response body, making them available on Insights PageView events.


513
514
515
516
517
518
519
520
# File 'lib/new_relic/agent.rb', line 513

def add_custom_attributes(params) #THREAD_LOCAL_ACCESS
  if params.is_a? Hash
    txn = Transaction.tl_current
    txn.add_custom_attributes(params) if txn
  else
    ::NewRelic::Agent.logger.warn("Bad argument passed to #add_custom_attributes. Expected Hash but got #{params.class}")
  end
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.


360
361
362
# File 'lib/new_relic/agent.rb', line 360

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.


328
329
330
# File 'lib/new_relic/agent.rb', line 328

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

#browser_timing_headerObject

This method returns a string suitable for inclusion in a page - known as 'manual instrumentation' for Real User Monitoring. Can return either a script tag with associated javascript, or in the case of disabled Real User Monitoring, an empty string

This is the header string - it should be placed as high in the page as is reasonably possible - that is, before any style or javascript inclusions, but after any header-related meta tags

In previous agents there was a corresponding footer required, but all the work is now done by this single method.


615
616
617
618
# File 'lib/new_relic/agent.rb', line 615

def browser_timing_header
  return "" unless agent
  agent.javascript_instrumentor.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 TransactionState.


433
434
435
436
437
438
439
440
441
442
# File 'lib/new_relic/agent.rb', line 433

def disable_all_tracing
  return yield unless agent

  begin
    agent.push_trace_execution_flag(false)
    yield
  ensure
    agent.pop_trace_execution_flag
  end
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

471
472
473
474
475
476
477
478
479
480
# File 'lib/new_relic/agent.rb', line 471

def disable_sql_recording
  return yield unless agent

  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


449
450
451
452
453
454
455
456
457
458
# File 'lib/new_relic/agent.rb', line 449

def disable_transaction_tracing
  return yield unless agent

  state = agent.set_record_tt(false)
  begin
    yield
  ensure
    agent.set_record_tt(state)
  end
end

#drop_buffered_dataObject

Clear out any data the agent has buffered but has not yet transmitted to the collector.


347
348
349
# File 'lib/new_relic/agent.rb', line 347

def drop_buffered_data
  agent.drop_buffered_data if agent
end

#get_transaction_nameObject

Get the name of the current running transaction. This is useful if you want to modify the default name.


558
559
560
561
562
563
564
# File 'lib/new_relic/agent.rb', line 558

def get_transaction_name #THREAD_LOCAL_ACCESS
  txn = Transaction.tl_current
  if txn
    namer = Instrumentation::ControllerInstrumentation::TransactionNamer
    txn.best_name.sub(Regexp.new("\\A#{Regexp.escape(namer.prefix_for_category(txn))}"), '')
  end
end

#ignore_apdexObject

This method disables the recording of Apdex metrics in the current transaction.


411
412
413
414
# File 'lib/new_relic/agent.rb', line 411

def ignore_apdex
  txn = NewRelic::Agent::Transaction.tl_current
  txn.ignore_apdex! if txn
end

#ignore_enduserObject

This method disables browser monitoring javascript injection in the current transaction.


421
422
423
424
# File 'lib/new_relic/agent.rb', line 421

def ignore_enduser
  txn = NewRelic::Agent::Transaction.tl_current
  txn.ignore_enduser! if txn
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.


201
202
203
204
205
206
207
# File 'lib/new_relic/agent.rb', line 201

def ignore_error_filter(&block)
  if block
    NewRelic::Agent::ErrorCollector.ignore_error_filter = block
  else
    NewRelic::Agent::ErrorCollector.ignore_error_filter
  end
end

#ignore_transactionObject

This method disables the recording of the current transaction. No metrics, traced errors, transaction traces, Insights events, slow SQL traces, or RUM injection will happen for this transaction.


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

def ignore_transaction
  txn = NewRelic::Agent::Transaction.tl_current
  txn.ignore! if txn
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.


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

def increment_metric(metric_name, amount=1) #THREAD_LOCAL_ACCESS
  return unless agent

  agent.stats_engine.tl_record_unscoped_metrics(metric_name) do |stats|
    stats.increment_count(amount)
  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.


298
299
300
301
# File 'lib/new_relic/agent.rb', line 298

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

Send an error to New Relic.

Any option keys other than the ones listed here are treated as :custom_params.

Note: Previous versions of the agent allowed passing :request_params, but those are now ignored. If you need to record the request parameters, call this method inside a transaction or pass the information in :custom_params.

Most of the time, you do not need to specify the :uri or :metric options; only pass them if you are calling notice_error outside a transaction.

Parameters:

  • exception (Exception)

    Error you wish to send

  • options (Hash) (defaults to: {})

    Modify how New Relic processes the error

Options Hash (options):

  • :custom_params (Hash)

    Custom parameters to attach to the trace

  • :trace_only (Boolean)

    Only record the error trace (do not affect error rate or Apdex status)

  • :uri (String)

    Request path, minus request params or query string (usually not needed)

  • :metric (String)

    Metric name associated with the transaction (usually not needed)


237
238
239
240
# File 'lib/new_relic/agent.rb', line 237

def notice_error(exception, options={})
  Transaction.notice_error(exception, options)
  nil # don't return a noticed error datastructure. it can only hurt.
end

#record_custom_event(event_type, event_attrs) ⇒ Object

Record a custom event to be sent to New Relic Insights. The recorded event will be buffered in memory until the next time the agent sends data to New Relic's servers.

If you want to be able to tie the information recorded via this call back to the web request or background job that it happened in, you may want to instead use the add_custom_attributes API call to attach attributes to the Transaction event that will automatically be generated for the request.

A timestamp will be automatically added to the recorded event when this method is called.

Parameters:

  • event_type (Symbol or String)

    The name of the event type to record. Event types must consist of only alphanumeric characters, '_', ':', or ' '.

  • event_attrs (Hash)

    A Hash of attributes to be attached to the event. Keys should be strings or symbols, and values may be strings, symbols, numeric values or booleans.


270
271
272
273
274
275
# File 'lib/new_relic/agent.rb', line 270

def record_custom_event(event_type, event_attrs)
  if agent && NewRelic::Agent.config[:'custom_insights_events.enabled']
    agent.custom_event_aggregator.record(event_type, event_attrs)
  end
  nil
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.


153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/new_relic/agent.rb', line 153

def record_metric(metric_name, value) #THREAD_LOCAL_ACCESS
  return unless agent

  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.tl_record_unscoped_metrics(metric_name, value)
end

#require_test_helperObject

Require agent testing helper methods


367
368
369
# File 'lib/new_relic/agent.rb', line 367

def require_test_helper
  require File.expand_path('../../../test/agent_helper', __FILE__)
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

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

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 => :middleware 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.


549
550
551
# File 'lib/new_relic/agent.rb', line 549

def set_transaction_name(name, options={})
  Transaction.set_overriding_transaction_name(name, options[:category])
end

#shutdown(options = {}) ⇒ Object

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

Parameters:

  • options (Hash) (defaults to: {})

    Unused options Hash, for back compatibility only


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

def shutdown(options={})
  agent.shutdown if agent
end