Module: NewRelic::Agent

Extended by:
Forwardable, Agent, SupportabilityHelper
Included in:
Agent
Defined in:
lib/new_relic/agent.rb,
lib/new_relic/agent/vm.rb,
lib/new_relic/agent/aws.rb,
lib/new_relic/agent/llm.rb,
lib/new_relic/agent/heap.rb,
lib/new_relic/agent/agent.rb,
lib/new_relic/agent/stats.rb,
lib/new_relic/agent/tracer.rb,
lib/new_relic/agent/logging.rb,
lib/new_relic/agent/sampler.rb,
lib/new_relic/agent/database.rb,
lib/new_relic/agent/hostname.rb,
lib/new_relic/agent/log_once.rb,
lib/new_relic/agent/monitors.rb,
lib/new_relic/agent/autostart.rb,
lib/new_relic/agent/harvester.rb,
lib/new_relic/agent/messaging.rb,
lib/new_relic/agent/attributes.rb,
lib/new_relic/agent/datastores.rb,
lib/new_relic/agent/deprecator.rb,
lib/new_relic/agent/event_loop.rb,
lib/new_relic/agent/obfuscator.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/vm/jruby_vm.rb,
lib/new_relic/agent/vm/snapshot.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/error_filter.rb,
lib/new_relic/agent/event_buffer.rb,
lib/new_relic/agent/health_check.rb,
lib/new_relic/agent/log_priority.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/vm/c_ruby_vm.rb,
lib/new_relic/agent/configuration.rb,
lib/new_relic/agent/llm/embedding.rb,
lib/new_relic/agent/llm/llm_event.rb,
lib/new_relic/agent/memory_logger.rb,
lib/new_relic/agent/method_tracer.rb,
lib/new_relic/agent/event_listener.rb,
lib/new_relic/agent/guid_generator.rb,
lib/new_relic/agent/error_collector.rb,
lib/new_relic/agent/instrumentation.rb,
lib/new_relic/agent/utilization/aws.rb,
lib/new_relic/agent/utilization/ecs.rb,
lib/new_relic/agent/utilization/gcp.rb,
lib/new_relic/agent/utilization/pcf.rb,
lib/new_relic/agent/adaptive_sampler.rb,
lib/new_relic/agent/attribute_filter.rb,
lib/new_relic/agent/database_adapter.rb,
lib/new_relic/agent/datastores/mongo.rb,
lib/new_relic/agent/datastores/redis.rb,
lib/new_relic/agent/event_aggregator.rb,
lib/new_relic/agent/linking_metadata.rb,
lib/new_relic/agent/noticeable_error.rb,
lib/new_relic/agent/utilization_data.rb,
lib/new_relic/agent/new_relic_service.rb,
lib/new_relic/agent/transaction/trace.rb,
lib/new_relic/agent/utilization/azure.rb,
lib/new_relic/agent/sampler_collection.rb,
lib/new_relic/agent/serverless_handler.rb,
lib/new_relic/agent/utilization/ecs_v4.rb,
lib/new_relic/agent/utilization/vendor.rb,
lib/new_relic/agent/database/obfuscator.rb,
lib/new_relic/agent/distributed_tracing.rb,
lib/new_relic/agent/encoding_normalizer.rb,
lib/new_relic/agent/local_log_decorator.rb,
lib/new_relic/agent/opentelemetry/trace.rb,
lib/new_relic/agent/parameter_filtering.rb,
lib/new_relic/agent/samplers/vm_sampler.rb,
lib/new_relic/agent/transaction/segment.rb,
lib/new_relic/agent/transaction/tracing.rb,
lib/new_relic/agent/transaction_metrics.rb,
lib/new_relic/agent/transaction_sampler.rb,
lib/new_relic/agent/attribute_processing.rb,
lib/new_relic/agent/internal_agent_error.rb,
lib/new_relic/agent/llm/response_headers.rb,
lib/new_relic/agent/log_event_aggregator.rb,
lib/new_relic/agent/log_event_attributes.rb,
lib/new_relic/agent/opentelemetry_bridge.rb,
lib/new_relic/agent/pipe_channel_manager.rb,
lib/new_relic/agent/samplers/cpu_sampler.rb,
lib/new_relic/agent/span_event_primitive.rb,
lib/new_relic/agent/agent_helpers/connect.rb,
lib/new_relic/agent/agent_helpers/harvest.rb,
lib/new_relic/agent/agent_helpers/startup.rb,
lib/new_relic/agent/configuration/manager.rb,
lib/new_relic/agent/http_clients/abstract.rb,
lib/new_relic/agent/http_clients/uri_util.rb,
lib/new_relic/agent/method_tracer_helpers.rb,
lib/new_relic/agent/opentelemetry/context.rb,
lib/new_relic/agent/span_event_aggregator.rb,
lib/new_relic/agent/agent_helpers/shutdown.rb,
lib/new_relic/agent/agent_helpers/transmit.rb,
lib/new_relic/agent/commands/agent_command.rb,
lib/new_relic/agent/error_event_aggregator.rb,
lib/new_relic/agent/error_trace_aggregator.rb,
lib/new_relic/agent/payload_metric_mapping.rb,
lib/new_relic/agent/prepend_supportability.rb,
lib/new_relic/agent/threading/agent_thread.rb,
lib/new_relic/agent/transaction/trace_node.rb,
lib/new_relic/agent/attribute_pre_filtering.rb,
lib/new_relic/agent/connect/request_builder.rb,
lib/new_relic/agent/custom_event_aggregator.rb,
lib/new_relic/agent/javascript_instrumentor.rb,
lib/new_relic/agent/priority_sampled_buffer.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/connect/response_handler.rb,
lib/new_relic/agent/datastores/metric_helper.rb,
lib/new_relic/agent/opentelemetry/trace/span.rb,
lib/new_relic/agent/stats_engine/gc_profiler.rb,
lib/new_relic/agent/threading/backtrace_node.rb,
lib/new_relic/agent/threading/thread_profile.rb,
lib/new_relic/agent/timestamp_sampled_buffer.rb,
lib/new_relic/agent/vm/monotonic_gc_profiler.rb,
lib/new_relic/agent/configuration/dotted_hash.rb,
lib/new_relic/agent/configuration/yaml_source.rb,
lib/new_relic/agent/opentelemetry/trace_patch.rb,
lib/new_relic/agent/transaction/trace_builder.rb,
lib/new_relic/agent/transaction/trace_context.rb,
lib/new_relic/agent/http_clients/curb_wrappers.rb,
lib/new_relic/agent/instrumentation/active_job.rb,
lib/new_relic/agent/instrumentation/queue_time.rb,
lib/new_relic/agent/new_relic_service/encoders.rb,
lib/new_relic/agent/opentelemetry/trace/tracer.rb,
lib/new_relic/agent/transaction_event_recorder.rb,
lib/new_relic/agent/configuration/manual_source.rb,
lib/new_relic/agent/configuration/mask_defaults.rb,
lib/new_relic/agent/configuration/server_source.rb,
lib/new_relic/agent/datastores/nosql_obfuscator.rb,
lib/new_relic/agent/http_clients/ethon_wrappers.rb,
lib/new_relic/agent/http_clients/excon_wrappers.rb,
lib/new_relic/agent/http_clients/httpx_wrappers.rb,
lib/new_relic/agent/instrumentation/grpc/helper.rb,
lib/new_relic/agent/llm/chat_completion_message.rb,
lib/new_relic/agent/llm/chat_completion_summary.rb,
lib/new_relic/agent/monitors/synthetics_monitor.rb,
lib/new_relic/agent/synthetics_event_aggregator.rb,
lib/new_relic/agent/threading/backtrace_service.rb,
lib/new_relic/agent/transaction_error_primitive.rb,
lib/new_relic/agent/transaction_event_primitive.rb,
lib/new_relic/agent/transaction_time_aggregator.rb,
lib/new_relic/agent/configuration/default_source.rb,
lib/new_relic/agent/database/obfuscation_helpers.rb,
lib/new_relic/agent/instrumentation/curb/prepend.rb,
lib/new_relic/agent/new_relic_service/marshaller.rb,
lib/new_relic/agent/samplers/delayed_job_sampler.rb,
lib/new_relic/agent/transaction/abstract_segment.rb,
lib/new_relic/agent/transaction_event_aggregator.rb,
lib/new_relic/agent/agent_helpers/special_startup.rb,
lib/new_relic/agent/commands/agent_command_router.rb,
lib/new_relic/agent/database/explain_plan_helpers.rb,
lib/new_relic/agent/http_clients/http_rb_wrappers.rb,
lib/new_relic/agent/instrumentation/active_record.rb,
lib/new_relic/agent/instrumentation/padrino/chain.rb,
lib/new_relic/agent/instrumentation/resque/helper.rb,
lib/new_relic/agent/instrumentation/sequel_helper.rb,
lib/new_relic/agent/opentelemetry/segments/server.rb,
lib/new_relic/agent/rules_engine/replacement_rule.rb,
lib/new_relic/agent/transaction/datastore_segment.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/ignore_actions.rb,
lib/new_relic/agent/instrumentation/memcache/dalli.rb,
lib/new_relic/agent/instrumentation/thread/prepend.rb,
lib/new_relic/agent/transaction/distributed_tracer.rb,
lib/new_relic/agent/transaction/request_attributes.rb,
lib/new_relic/agent/opentelemetry/transaction_patch.rb,
lib/new_relic/agent/rules_engine/segment_terms_rule.rb,
lib/new_relic/agent/transaction/distributed_tracing.rb,
lib/new_relic/agent/commands/thread_profiler_session.rb,
lib/new_relic/agent/configuration/environment_source.rb,
lib/new_relic/agent/datastores/mongo/event_formatter.rb,
lib/new_relic/agent/http_clients/async_http_wrappers.rb,
lib/new_relic/agent/http_clients/httpclient_wrappers.rb,
lib/new_relic/agent/instrumentation/middleware_proxy.rb,
lib/new_relic/agent/instrumentation/net_http/prepend.rb,
lib/new_relic/agent/monitors/inbound_request_monitor.rb,
lib/new_relic/agent/opentelemetry/segments/datastore.rb,
lib/new_relic/agent/serverless_handler_event_sources.rb,
lib/new_relic/agent/agent_helpers/start_worker_thread.rb,
lib/new_relic/agent/distributed_tracing/trace_context.rb,
lib/new_relic/agent/instrumentation/stripe_subscriber.rb,
lib/new_relic/agent/new_relic_service/json_marshaller.rb,
lib/new_relic/agent/opentelemetry/context/propagation.rb,
lib/new_relic/agent/transaction/slowest_sample_buffer.rb,
lib/new_relic/agent/configuration/event_harvest_config.rb,
lib/new_relic/agent/configuration/high_security_source.rb,
lib/new_relic/agent/datastores/mongo/metric_translator.rb,
lib/new_relic/agent/instrumentation/middleware_tracing.rb,
lib/new_relic/agent/transaction/message_broker_segment.rb,
lib/new_relic/agent/instrumentation/delayed_job/prepend.rb,
lib/new_relic/agent/instrumentation/grpc/client/prepend.rb,
lib/new_relic/agent/opentelemetry/trace/tracer_provider.rb,
lib/new_relic/agent/database/postgres_explain_obfuscator.rb,
lib/new_relic/agent/instrumentation/active_record_helper.rb,
lib/new_relic/agent/instrumentation/curb/instrumentation.rb,
lib/new_relic/agent/instrumentation/rack/instrumentation.rb,
lib/new_relic/agent/instrumentation/rake/instrumentation.rb,
lib/new_relic/agent/instrumentation/tilt/instrumentation.rb,
lib/new_relic/agent/monitors/distributed_tracing_monitor.rb,
lib/new_relic/agent/opentelemetry/abstract_segment_patch.rb,
lib/new_relic/agent/opentelemetry/segments/http_external.rb,
lib/new_relic/agent/transaction/external_request_segment.rb,
lib/new_relic/agent/transaction/synthetics_sample_buffer.rb,
lib/new_relic/agent/instrumentation/active_job_subscriber.rb,
lib/new_relic/agent/instrumentation/active_record_prepend.rb,
lib/new_relic/agent/instrumentation/bunny/instrumentation.rb,
lib/new_relic/agent/transaction/transaction_sample_buffer.rb,
lib/new_relic/agent/configuration/sampler_config_validator.rb,
lib/new_relic/agent/instrumentation/action_view_subscriber.rb,
lib/new_relic/agent/instrumentation/logger/instrumentation.rb,
lib/new_relic/agent/instrumentation/thread/instrumentation.rb,
lib/new_relic/agent/instrumentation/action_cable_subscriber.rb,
lib/new_relic/agent/instrumentation/action_mailer_subscriber.rb,
lib/new_relic/agent/instrumentation/active_record_subscriber.rb,
lib/new_relic/agent/instrumentation/net_http/instrumentation.rb,
lib/new_relic/agent/instrumentation/notifications_subscriber.rb,
lib/new_relic/agent/instrumentation/rails3/action_controller.rb,
lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb,
lib/new_relic/agent/distributed_tracing/trace_context_payload.rb,
lib/new_relic/agent/instrumentation/action_mailbox_subscriber.rb,
lib/new_relic/agent/instrumentation/active_storage_subscriber.rb,
lib/new_relic/agent/instrumentation/active_support_subscriber.rb,
lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb,
lib/new_relic/agent/instrumentation/action_dispatch_subscriber.rb,
lib/new_relic/agent/instrumentation/controller_instrumentation.rb,
lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb,
lib/new_relic/agent/instrumentation/active_record_notifications.rb,
lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb,
lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb,
lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb,
lib/new_relic/agent/instrumentation/grpc/client/request_wrapper.rb,
lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb,
lib/new_relic/agent/instrumentation/roda/roda_transaction_namer.rb,
lib/new_relic/agent/instrumentation/action_controller_subscriber.rb,
lib/new_relic/agent/instrumentation/grpc/server/rpc_desc_prepend.rb,
lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb,
lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb,
lib/new_relic/agent/instrumentation/grpc/server/rpc_server_prepend.rb,
lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb,
lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb,
lib/new_relic/agent/opentelemetry/context/propagation/trace_propagator.rb,
lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb,
lib/new_relic/agent/instrumentation/active_support_logger/instrumentation.rb

Overview

This file is distributed under New Relic’s license terms. See github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. frozen_string_literal: true

Defined Under Namespace

Modules: AgentHelpers, AttributePreFiltering, AttributeProcessing, Autostart, Aws, Commands, Configuration, Connect, Database, Datastores, Deprecator, DistributedTraceAttributes, DistributedTraceMetrics, DistributedTraceTransportType, DistributedTracing, EncodingNormalizer, GuidGenerator, HTTPClients, Hostname, Instrumentation, LinkingMetadata, Llm, LocalLogDecorator, LogOnce, LogPriority, Logging, Messaging, MethodTracer, MethodTracerHelpers, OpenTelemetry, ParameterFiltering, PayloadMetricMapping, PipeChannelManager, PrependSupportability, Samplers, SpanEventPrimitive, SystemInfo, Threading, TransactionErrorPrimitive, TransactionEventPrimitive, TransactionTimeAggregator, Utilization, VM Classes: AdaptiveSampler, Agent, AgentLogger, AttributeFilter, AttributeFilterRule, Attributes, AuditLogger, AutomaticTracerParseException, AutomaticTracerTraceException, CustomEventAggregator, DatabaseAdapter, DistributedTracePayload, ErrorCollector, ErrorEventAggregator, ErrorFilter, ErrorTraceAggregator, EventAggregator, EventBuffer, EventListener, EventLoop, ForceDisconnectException, ForceRestartException, Harvester, HealthCheck, Heap, InboundRequestMonitor, InternalAgentError, JavaScriptInstrumentor, LLM, LicenseException, LogEventAggregator, LogEventAttributes, MemoryLogger, Monitors, NewRelicService, NoticeableError, NullLogger, Obfuscator, OpenTelemetryBridge, PipeService, PrioritySampledBuffer, RulesEngine, Sampler, SamplerCollection, SerializationError, ServerConnectionException, ServerlessHandler, ServerlessHandlerEventSources, SlowSql, SpanEventAggregator, SqlSampler, SqlTrace, StartupLogger, Stats, StatsEngine, StatsHash, SyntheticsEventAggregator, SyntheticsMonitor, TimestampSampledBuffer, TraceContextPayload, Tracer, Transaction, TransactionEventAggregator, TransactionEventRecorder, TransactionMetrics, TransactionSampler, TransactionSqlData, UnrecoverableAgentException, UnrecoverableServerException, UtilizationData, WorkerLoop

Recording custom metrics collapse

SUPPORTABILITY_INCREMENT_METRIC =
'Supportability/API/increment_metric'.freeze

Trace and Entity metadata collapse

TRACE_ID_KEY =
'trace.id'.freeze
SPAN_ID_KEY =
'span.id'.freeze
ENTITY_NAME_KEY =
'entity.name'.freeze
ENTITY_TYPE_KEY =
'entity.type'.freeze
ENTITY_GUID_KEY =
'entity.guid'.freeze
HOSTNAME_KEY =
'hostname'.freeze
ENTITY_TYPE =
'SERVICE'.freeze

Constant Summary collapse

UNKNOWN_METRIC =

placeholder name used when we cannot determine a transaction’s name

'(unknown)'.freeze
LLM_FEEDBACK_MESSAGE =
'LlmFeedbackMessage'
AUTOMATIC_TRACER_MAX_ATTEMPTS =

give the observed app time to load the code that automatic tracers have been configured for

60
VALID_CUSTOM_EVENT_TYPE =

Event types must consist of only alphanumeric characters, ‘_’, ‘:’, or ‘ ’.

/\A[\w: ]+\z/

Constants included from SupportabilityHelper

SupportabilityHelper::API_SUPPORTABILITY_METRICS, SupportabilityHelper::API_SUPPORTABILITY_PREFIX

Instance Attribute Summary collapse

Recording custom metrics collapse

Recording custom errors collapse

Recording custom Insights events collapse

LLM callbacks collapse

Manual agent configuration and startup/shutdown collapse

Ignoring or excluding data collapse

Adding custom attributes to traces collapse

Transaction naming collapse

Trace and Entity metadata collapse

Manual browser monitoring configuration collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from SupportabilityHelper

record_api_supportability_metric, valid_api_argument_class?

Instance Attribute Details

#error_group_callbackObject (readonly)



122
123
124
# File 'lib/new_relic/agent.rb', line 122

def error_group_callback
  @error_group_callback
end

#llm_token_count_callbackObject (readonly)



123
124
125
# File 'lib/new_relic/agent.rb', line 123

def llm_token_count_callback
  @llm_token_count_callback
end

Class Method Details

.add_automatic_method_tracers(arr) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



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

def self.add_automatic_method_tracers(arr)
  return unless arr
  return arr if arr.respond_to?(:empty?) && arr.empty?

  arr = arr.split(/\s*,\s*/) if arr.is_a?(String)

  add_tracers_once_methods_are_defined(arr.dup)

  arr
end

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

Parameters:

  • params (Hash)

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



832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
# File 'lib/new_relic/agent.rb', line 832

def add_custom_attributes(params) # THREAD_LOCAL_ACCESS
  record_api_supportability_metric(:add_custom_attributes)

  unless params.is_a?(Hash)
    ::NewRelic::Agent.logger.warn("Bad argument passed to #add_custom_attributes. Expected Hash but got #{params.class}")
    return
  end

  if NewRelic::Agent.agent&.serverless?
    ::NewRelic::Agent.logger.warn('Custom attributes are not supported in serverless mode')
    return
  end

  Transaction.tl_current&.add_custom_attributes(params)
  segment = ::NewRelic::Agent::Tracer.current_segment
  add_new_segment_attributes(params, segment) if segment
end

.add_custom_log_attributes(params) ⇒ Object

Add global custom attributes to log events for the current agent instance. As these attributes are global to the agent instance, they will be attached to all log events generated by the agent, and this methods usage isn’t suitable for setting dynamic values.

Parameters:

  • params (Hash)

    A Hash of attributes to attach to log events. The agent accepts up to 240 custom log event attributes.

    Keys will be coerced into Strings and must be less than 256 characters. Keys longer than 255 characters will be truncated.

    Values may be Strings, Symbols, numeric values or Booleans and must be less than 4095 characters. If the value is a String or a Symbol, values longer than 4094 characters will be truncated. If the value exceeds 4094 characters and is of a different class, the attribute pair will be dropped.

    This API can be called multiple times. If the same key is passed more than once, the value associated with the last call will be preserved.

    Attribute pairs with empty or nil contents will be dropped.



914
915
916
917
918
919
920
921
922
# File 'lib/new_relic/agent.rb', line 914

def add_custom_log_attributes(params)
  record_api_supportability_metric(:add_custom_log_attributes)

  if params.is_a?(Hash)
    NewRelic::Agent.agent.log_event_aggregator.add_custom_attributes(params)
  else
    NewRelic::Agent.logger.warn("Bad argument passed to #add_custom_log_attributes. Expected Hash but got #{params.class}.")
  end
end

.add_custom_span_attributes(params) ⇒ Object

Add custom attributes to the span event for the current span. Attributes will be visible on spans in the New Relic Distributed Tracing UI and on span events in New Relic Insights.

Custom attributes will not be transmitted when high_security setting is enabled or custom_attributes setting is disabled.

Parameters:

  • params (Hash)

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

See Also:



872
873
874
875
876
877
878
879
880
881
882
# File 'lib/new_relic/agent.rb', line 872

def add_custom_span_attributes(params)
  record_api_supportability_metric(:add_custom_span_attributes)

  if params.is_a?(Hash)
    if segment = NewRelic::Agent::Tracer.current_segment
      segment.add_custom_attributes(params)
    end
  else
    ::NewRelic::Agent.logger.warn("Bad argument passed to #add_custom_span_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.



686
687
688
689
# File 'lib/new_relic/agent.rb', line 686

def add_instrumentation(file_pattern)
  record_api_supportability_metric(:add_instrumentation)
  NewRelic::Control.instance.add_instrumentation(file_pattern)
end

.add_tracers_once_methods_are_defined(notations) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

spawn a thread that will attempt to establish a tracer for each of the configured methods. the thread will continue to keep trying with each tracer until one of the following happens:

- the tracer is successfully established
- the configured method string couldn't be parsed
- establishing a tracer for a successfully parsed string failed
- the maximum number of attempts has been reached

the thread will only be spawned once per agent initialization, to account for configuration reloading scenarios.



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/new_relic/agent.rb', line 198

def self.add_tracers_once_methods_are_defined(notations)
  # this class method can be invoked multiple times at agent startup, so
  # we return asap here instead of using a traditional memoization of
  # waiting for the method's body to finish being executed
  if defined?(@add_tracers_once_methods_are_defined)
    return
  else
    @add_tracers_once_methods_are_defined = true
  end

  Thread.new do
    AUTOMATIC_TRACER_MAX_ATTEMPTS.times do
      notations.delete_if { |notation| prep_tracer_for(notation) }

      break if notations.empty?

      sleep 0.5
    end
  end
end

.add_transaction_log_attributes(params) ⇒ Object

Add transaction-scoped custom attributes to log events for the current transaction. These attributes will only be applied to logs created within the scope of the current transaction.

Parameters:

  • params (Hash)

    A Hash of attributes to attach to log events in the current transaction. The agent accepts up to 240 custom log event attributes per transaction.

    Keys will be coerced into Strings and must be less than 256 characters. Keys longer than 255 characters will be truncated.

    Values may be Strings, Symbols, numeric values or Booleans and must be less than 4095 characters. If the value is a String or a Symbol, values longer than 4094 characters will be truncated. If the value exceeds 4094 characters and is of a different class, the attribute pair will be dropped.

    This API can be called multiple times within a transaction. If the same key is passed more than once, the value associated with the last call will be preserved.

    Attribute pairs with empty or nil contents will be dropped.

    If called outside of a transaction context, the method will log a warning and return without adding attributes.



957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
# File 'lib/new_relic/agent.rb', line 957

def add_transaction_log_attributes(params)
  record_api_supportability_metric(:add_transaction_log_attributes)

  unless params.is_a?(Hash)
    ::NewRelic::Agent.logger.warn("Bad argument passed to #add_transaction_log_attributes. Expected Hash but got #{params.class}")
    return
  end

  transaction = Transaction.tl_current
  if transaction
    transaction.add_transaction_log_attributes(params)
  else
    ::NewRelic::Agent.logger.warn('add_transaction_log_attributes called outside of transaction context. Attributes will be ignored.')
  end
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.



646
647
648
649
650
# File 'lib/new_relic/agent.rb', line 646

def after_fork(options = {})
  record_api_supportability_metric(:after_fork)
  # the following line needs else branch coverage
  agent.after_fork(options) if agent # rubocop:disable Style/SafeNavigation
end

.browser_timing_header(nonce = nil) ⇒ Object

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.

Parameters:

  • nonce (String) (defaults to: nil)

    The nonce to use in the javascript tag for browser instrumentation



1134
1135
1136
1137
1138
1139
1140
# File 'lib/new_relic/agent.rb', line 1134

def browser_timing_header(nonce = nil)
  record_api_supportability_metric(:browser_timing_header)

  return EMPTY_STR unless agent

  agent.javascript_instrumentor.browser_timing_header(nonce)
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 Tracer::State.



768
769
770
771
772
773
774
775
776
777
778
779
# File 'lib/new_relic/agent.rb', line 768

def disable_all_tracing
  record_api_supportability_metric(: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


793
794
795
796
797
798
799
800
801
802
803
804
# File 'lib/new_relic/agent.rb', line 793

def disable_sql_recording
  record_api_supportability_metric(:disable_sql_recording)

  return yield unless agent

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

.drop_buffered_dataObject

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



670
671
672
673
674
# File 'lib/new_relic/agent.rb', line 670

def drop_buffered_data
  # the following line needs else branch coverage
  agent.drop_buffered_data if agent # rubocop:disable Style/SafeNavigation
  record_api_supportability_metric(:drop_buffered_data)
end

.get_transaction_nameObject

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



1035
1036
1037
1038
1039
1040
1041
1042
1043
# File 'lib/new_relic/agent.rb', line 1035

def get_transaction_name # THREAD_LOCAL_ACCESS
  record_api_supportability_metric(:get_transaction_name)

  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.



744
745
746
747
# File 'lib/new_relic/agent.rb', line 744

def ignore_apdex
  record_api_supportability_metric(:ignore_apdex)
  NewRelic::Agent::Transaction.tl_current&.ignore_apdex!
end

.ignore_enduserObject

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



755
756
757
758
# File 'lib/new_relic/agent.rb', line 755

def ignore_enduser
  record_api_supportability_metric(:ignore_enduser)
  NewRelic::Agent::Transaction.tl_current&.ignore_enduser!
end

.ignore_error_filter(&block) ⇒ Object

Set a filter to be applied to errors that the Ruby agent will track. The block should evaluate 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.



372
373
374
375
376
377
378
379
380
# File 'lib/new_relic/agent.rb', line 372

def ignore_error_filter(&block)
  record_api_supportability_metric(:ignore_error_filter)

  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.



733
734
735
736
# File 'lib/new_relic/agent.rb', line 733

def ignore_transaction
  record_api_supportability_metric(:ignore_transaction)
  NewRelic::Agent::Transaction.tl_current&.ignore!
end

.increment_metric(metric_name, amount = 1) ⇒ Object

Increment a simple counter metric.

metric_name should be a String that follows a slash separated path convention. Application specific metrics should begin with “Custom/”. amount (optional) should be a Numeric value to increment. Defaults to 1.

This method is safe to use from any thread.



344
345
346
347
348
349
350
351
352
353
354
# File 'lib/new_relic/agent.rb', line 344

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

  if amount == 1
    metrics = [metric_name, SUPPORTABILITY_INCREMENT_METRIC]
    agent.stats_engine.tl_record_unscoped_metrics(metrics) { |stats| stats.increment_count }
  else
    agent.stats_engine.tl_record_unscoped_metrics(metric_name) { |stats| stats.increment_count(amount) }
    agent.stats_engine.tl_record_unscoped_metrics(SUPPORTABILITY_INCREMENT_METRIC) { |stats| stats.increment_count }
  end
end

.linking_metadataObject

Returns a new hash containing trace and entity metadata that can be used to relate data to a trace or to an entity in APM.

This hash includes:

  • trace.id - The current trace id, if there is a current trace id. This value may be omitted.

  • span.id - The current span id, if there is a current span. This value may be omitted.

  • entity.name - The name of the current application. This is read from the app_name key in your config. If there are multiple application names, the first one is used.

  • entity.type - The entity type is hardcoded to the string ‘SERVICE’.

  • entity.guid - The guid of the current entity.

  • hostname - The fully qualified hostname.



1106
1107
1108
1109
1110
1111
# File 'lib/new_relic/agent.rb', line 1106

def 
   = Hash.new
  LinkingMetadata.()
  LinkingMetadata.()
  
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.



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

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))
  record_api_supportability_metric(:manual_start)
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

  • :expected (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)



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

def notice_error(exception, options = {})
  record_api_supportability_metric(:notice_error)

  Transaction.notice_error(exception, options)
  nil # don't return a noticed error data structure. it can only hurt.
end

.prep_tracer_for(fully_qualified_method_notation) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

returns ‘true` if the notation string has either been successfully processed or raised an error during processing. returns `false` if the string seems good but the (customer) code to be traced has not yet been loaded into the Ruby VM



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/new_relic/agent.rb', line 225

def self.prep_tracer_for(fully_qualified_method_notation)
  delimiters = fully_qualified_method_notation.scan(/\.|#/)
  raise AutomaticTracerParseException.new("Expected exactly one '.' or '#' delimiter.") unless delimiters.size == 1

  delimiter = delimiters.first
  namespace, method_name = fully_qualified_method_notation.split(delimiter)
  unless namespace && !namespace.empty?
    raise AutomaticTracerParseException.new("Nothing found to the left of the #{delimiter} delimiter.")
  end
  unless method_name && !method_name.empty?
    raise AutomaticTracerParseException.new("Nothing found to the right of the #{delimiter} delimiter.")
  end

  begin
    klass = ::NewRelic::LanguageSupport.constantize(namespace)
    return false unless klass

    klass_to_trace = delimiter.eql?('.') ? klass.singleton_class : klass
    add_or_defer_method_tracer(klass_to_trace, method_name, nil, {})
  rescue StandardError => e
    raise AutomaticTracerTraceException.new("#{e.class} - #{e.message}")
  end

  true
rescue AutomaticTracerParseException => e
  NewRelic::Agent.logger.error('Unable to parse out a usable method name to trace. Expected a valid, fully ' \
                               "qualified method notation. Got: '#{fully_qualified_method_notation}'. " \
                               "Error: #{e.message}")
  true
rescue AutomaticTracerTraceException => e
  NewRelic::Agent.logger.error('Unable to automatically apply a tracer to method ' \
                               "'#{fully_qualified_method_notation}'. Error: #{e.message}")
  true
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.



489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/new_relic/agent.rb', line 489

def record_custom_event(event_type, event_attrs)
  unless event_type.to_s.match?(VALID_CUSTOM_EVENT_TYPE)
    raise ArgumentError, "Invalid event_type: '#{event_type}'. Event types must consist of only alphanumeric characters, '_', ':', or ' '."
  end

  record_api_supportability_metric(:record_custom_event)

  if agent && NewRelic::Agent.config[:'custom_insights_events.enabled']
    agent.custom_event_aggregator.record(event_type, event_attrs)
  end

  nil
end

.record_llm_feedback_event(trace_id:, rating:, category: nil, message: nil, metadata: NewRelic::EMPTY_HASH) ⇒ Object

Records user feedback events for LLM applications. This API must pass the current trace id as a parameter, which can be obtained using:

NewRelic::Agent::Tracer.current_trace_id

Parameters:

  • ID (String)

    of the trace where the chat completion(s) related to the feedback occurred.

  • Rating (String or Integer)

    provided by an end user (ex: “Good“, ”Bad”, 1, 2, 5, 8, 10).

  • Category (optional, String)

    of the feedback as provided by the end user (ex: “informative”, “inaccurate”).

  • start_time (optional, String)

    Freeform text feedback from an end user.

  • Set (optional, Hash)

    of key-value pairs to store any other desired data to submit with the feedback event.



526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/new_relic/agent.rb', line 526

def record_llm_feedback_event(trace_id:,
  rating:,
  category: nil,
  message: nil,
  metadata: NewRelic::EMPTY_HASH)

  record_api_supportability_metric(:record_llm_feedback_event)
  unless NewRelic::Agent.config[:'distributed_tracing.enabled']
    return NewRelic::Agent.logger.error('Distributed tracing must be enabled to record LLM feedback')
  end

  feedback_message_event = {
    'trace_id': trace_id,
    'rating': rating,
    'category': category,
    'message': message,
    'id': NewRelic::Agent::GuidGenerator.generate_guid,
    'ingest_source': NewRelic::Agent::Llm::LlmEvent::INGEST_SOURCE
  }
  feedback_message_event.merge!() unless .empty?

  NewRelic::Agent.record_custom_event(LLM_FEEDBACK_MESSAGE, feedback_message_event)
rescue ArgumentError
  raise
rescue => exception
  NewRelic::Agent.logger.error('record_llm_feedback_event', exception)
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.



300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/new_relic/agent.rb', line 300

def record_metric(metric_name, value) # THREAD_LOCAL_ACCESS
  record_api_supportability_metric(:record_metric)

  return unless agent

  if value.is_a?(Hash)
    stats = NewRelic::Agent::Stats.new
    value = stats.hash_merge(value)
  end

  agent.stats_engine.tl_record_unscoped_metrics(metric_name, value)
end

.require_test_helperObject

Require agent testing helper methods



695
696
697
698
# File 'lib/new_relic/agent.rb', line 695

def require_test_helper
  record_api_supportability_metric(:require_test_helper)
  require File.expand_path('../../../test/agent_helper', __FILE__)
end

.set_error_group_callback(callback_proc) ⇒ Object

Set a callback proc for determining an error’s error group name

Typically this method should be called only once to set a callback for use with all noticed errors. If it is called multiple times, each new callback given will replace the old one.

The proc will be called with a single hash as its input argument and is expected to return a string representing the desired error group.

see docs.newrelic.com/docs/errors-inbox/errors-inbox/#groups

The hash passed to the customer defined callback proc has the following keys:

:error => The Ruby error class instance, likely inheriting from

StandardError. Call `#class`, `#message`, and `#backtrace` on
the error object to retrieve the error's class, message, and
backtrace.

:customAttributes => Any customer defined custom attributes that have been

associated with the current transaction.

:‘request.uri’ => The current request URI if available :‘http.statusCode’ => The HTTP status code (200, 404, etc.) if available :‘http.method’ => The HTTP method (GET, PUT, etc.) if available :‘error.expected’ => Whether (true) or not (false) the error was expected :options => The options hash passed to ‘NewRelic::Agent.notice_error`

Parameters:

  • callback_proc (Proc)

    the callback proc



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

def set_error_group_callback(callback_proc)
  unless callback_proc.is_a?(Proc)
    NewRelic::Agent.logger.error("#{self}.#{__method__}: expected an argument of type Proc, " \
                                 "got #{callback_proc.class}")
    return
  end

  record_api_supportability_metric(:set_error_group_callback)
  @error_group_callback = callback_proc
end

.set_llm_token_count_callback(callback_proc) ⇒ Object

Set a callback proc for calculating ‘token_count` attributes for LlmEmbedding and LlmChatCompletionMessage events

This method should be called only once to set a callback for use with all LLM token calculations. If it is called multiple times, each new callback will replace the old one.

The proc will be called with a single hash as its input argument and must return an Integer representing the number of tokens used for that particular prompt, completion message, or embedding. Values less than or equal to 0 will not be attached to an event.

The hash has the following keys:

:model => [String] The name of the LLM model :content => [String] The message content or prompt

Parameters:

  • callback_proc (Proc)

    the callback proc



580
581
582
583
584
585
586
587
588
589
# File 'lib/new_relic/agent.rb', line 580

def set_llm_token_count_callback(callback_proc)
  unless callback_proc.is_a?(Proc)
    NewRelic::Agent.logger.error("#{self}.#{__method__}: expected an argument of type Proc, " \
                                 "got #{callback_proc.class}")
    return
  end

  record_api_supportability_metric(:set_llm_token_count_callback)
  @llm_token_count_callback = callback_proc
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


717
718
719
720
# File 'lib/new_relic/agent.rb', line 717

def set_sql_obfuscator(type = :replace, &block)
  record_api_supportability_metric(:set_sql_obfuscator)
  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. The following are the only valid categories:

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



1024
1025
1026
1027
# File 'lib/new_relic/agent.rb', line 1024

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

.set_user_id(user_id) ⇒ Object

Set the user id for the current transaction. When present, this value will be included in the agent attributes for transaction and error events as ‘enduser.id’.

Parameters:

  • user_id (String)

    The user id to add to the current transaction attributes



979
980
981
982
983
984
985
986
987
988
989
990
991
992
# File 'lib/new_relic/agent.rb', line 979

def set_user_id(user_id)
  record_api_supportability_metric(:set_user_id)

  if user_id.nil? || user_id.empty?
    ::NewRelic::Agent.logger.warn('NewRelic::Agent.set_user_id called with a nil or empty user id.')
    return
  end

  default_destinations = NewRelic::Agent::AttributeFilter::DST_TRANSACTION_TRACER |
    NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS |
    NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR

  NewRelic::Agent::Transaction.add_agent_attribute(:'enduser.id', user_id, default_destinations)
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



660
661
662
663
# File 'lib/new_relic/agent.rb', line 660

def shutdown(options = {})
  record_api_supportability_metric(:shutdown)
  agent&.shutdown
end

Instance Method Details

#add_deferred_method_tracers_nowObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



261
262
263
264
265
266
267
268
269
# File 'lib/new_relic/agent.rb', line 261

def add_deferred_method_tracers_now
  @tracer_lock.synchronize do
    @tracer_queue.each do |receiver, method_name, metric_name, options|
      receiver.send(:_nr_add_method_tracer_now, method_name, metric_name, options)
    end

    @tracer_queue = []
  end
end

#add_new_segment_attributes(params, segment) ⇒ Object



850
851
852
853
854
855
856
# File 'lib/new_relic/agent.rb', line 850

def add_new_segment_attributes(params, segment)
  # Make sure not to override existing segment-level custom attributes
  segment_custom_keys = segment.attributes.custom_attributes.keys.map(&:to_sym)
  segment.add_custom_attributes(params.reject do |k, _v|
    segment_custom_keys.include?(k.to_sym) if k.respond_to?(:to_sym) # param keys can be integers
  end)
end

#add_or_defer_method_tracer(receiver, method_name, metric_name, options) ⇒ Object

A third-party class may call add_method_tracer before the agent is initialized; these methods enable us to defer these calls until we have started up and can process them.



163
164
165
166
167
168
169
170
171
172
173
# File 'lib/new_relic/agent.rb', line 163

def add_or_defer_method_tracer(receiver, method_name, metric_name, options)
  @tracer_lock.synchronize do
    options[:code_information] = NewRelic::Agent::MethodTracerHelpers.code_information(receiver, method_name)

    if @agent
      receiver.send(:_nr_add_method_tracer_now, method_name, metric_name, options)
    else
      @tracer_queue << [receiver, method_name, metric_name, options]
    end
  end
end

#agentObject Also known as: instance

The singleton Agent instance. Used internally.



134
135
136
137
138
139
140
# File 'lib/new_relic/agent.rb', line 134

def agent # :nodoc:
  return @agent if @agent

  NewRelic::Agent.logger.debug("Agent unavailable as it hasn't been started.")
  NewRelic::Agent.logger.debug(caller.join("\n"))
  nil
end

#agent=(new_instance) ⇒ Object

:nodoc:



142
143
144
145
# File 'lib/new_relic/agent.rb', line 142

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

#base_name(klass_name) ⇒ Object

see ActiveSupport::Inflector.demodulize



324
325
326
327
328
# File 'lib/new_relic/agent.rb', line 324

def base_name(klass_name)
  return klass_name unless ridx = klass_name.rindex('::')

  klass_name[(ridx + 2), klass_name.length]
end

#configObject



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

def config
  @config ||= Configuration::Manager.new
end

#loggerObject

Primary interface to logging is fronted by this accessor Access via ::NewRelic::Agent.logger



151
152
153
# File 'lib/new_relic/agent.rb', line 151

def logger
  @logger || StartupLogger.instance
end

#logger=(log) ⇒ Object



155
156
157
# File 'lib/new_relic/agent.rb', line 155

def logger=(log)
  @logger = log
end

#notify(event_type, *args) ⇒ Object

Fire an event of the specified event_type, passing it an the given args to any registered handlers.



1072
1073
1074
1075
1076
# File 'lib/new_relic/agent.rb', line 1072

def notify(event_type, *args)
  agent.events.notify(event_type, *args)
rescue
  NewRelic::Agent.logger.debug('Ignoring exception during %p event notification' % [event_type])
end

#record_instrumentation_invocation(library) ⇒ Object



319
320
321
# File 'lib/new_relic/agent.rb', line 319

def record_instrumentation_invocation(library)
  record_metric_once("Supportability/#{library}/Invoked")
end

#record_metric_once(metric_name, value = 0.0) ⇒ Object



313
314
315
316
317
# File 'lib/new_relic/agent.rb', line 313

def record_metric_once(metric_name, value = 0.0)
  return unless @metrics_already_recorded.add?(metric_name)

  record_metric(metric_name, value)
end

#reset_configObject

For testing Important that we don’t change the instance or we orphan callbacks



277
278
279
# File 'lib/new_relic/agent.rb', line 277

def reset_config
  config.reset_to_defaults
end

#subscribe(event_type, &handler) ⇒ Object

Subscribe to events of event_type, calling the given handler when one is sent.



1066
1067
1068
# File 'lib/new_relic/agent.rb', line 1066

def subscribe(event_type, &handler)
  agent.events.subscribe(event_type, &handler)
end

#tl_is_execution_traced?Boolean

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

Returns:

  • (Boolean)


809
810
811
# File 'lib/new_relic/agent.rb', line 809

def tl_is_execution_traced?
  NewRelic::Agent::Tracer.state.is_execution_traced?
end

#with_database_metric_name(model, method = nil, product = nil, &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 reentrant.

identify the operation with.

Parameters:

  • model (String, Class, #to_s)

    the DB model class

  • method (String) (defaults to: nil)

    the name of the finder method or other method to



1056
1057
1058
1059
1060
1061
1062
# File 'lib/new_relic/agent.rb', line 1056

def with_database_metric_name(model, method = nil, product = nil, &block)
  if txn = Tracer.current_transaction
    txn.with_database_metric_name(model, method, product, &block)
  else
    yield
  end
end