• /
  • Log in

Guide to using the Java agent API

The New Relic Java agent API lets you control, customize, and extend the functionality of the APM Java agent. This API consists of:

  • Static methods on the com.newrelic.api.agent.NewRelic class
  • A @Trace annotation for implementing custom instrumentation
  • A hierarchy of API objects providing additional functionality

Use this API to set up custom instrumentation of your Java app and collect more in-depth data. For detailed information about this API, see the complete Javadoc on GitHub.

Another way to set up custom instrumentation is to use XML instrumentation. The XML option is simpler and does not require modification of your app code, but it lacks the complete functionality of the Java agent API.

Important

For best results when using the API, ensure that you have the latest Java agent release. Several APIs used in the examples require Java agent 6.4.0 or higher.

For all available New Relic APIs, see Intro to APIs.

Use the API

To access the API class, add newrelic-api.jar to your application class path. The jar is in the New Relic Java agent's installation zip file. You can call the API when the Java agent is not running. The API methods are just stubs; the implementation is added when the Java agent loads the class.

Transactions

To instrument Transactions in your application, use the following APIs.

If you want to...

Use this

Create a Transaction when New Relic does not create one automatically

@Trace(dispatcher = true) on the method that encompasses the work to be reported. When this annotation is used on a method within the context of an existing transaction, this will not start a new transaction, but rather include the method in the existing transaction.

Capture the duration of a method that New Relic does not automatically trace

@Trace() on the method you want to time.

Set the name of the current Transaction

NewRelic.setTransactionName(...)

Start the timer for the response time of the current Transaction and to cause a Transaction you create to be reported as a Web transaction, rather than as an Other transaction

NewRelic.setRequestAndReponse(...)

Add custom attributes to Transactions and TransactionEvents

NewRelic.addCustomParameter(...)

Prevent a Transaction from being reported to New Relic

NewRelic.ignoreTransaction()

Exclude a Transaction when calculating your app's Apdex score

NewRelic.ignoreApdex()

Instrument asynchronous work

For detailed information, see Java agent API for asynchronous applications.

If you want to...

Use this

Trace an asynchronous method if it is linked to an existing Transaction...

@Trace(async = true)

Link the Transaction associated with the Token on the current thread...

Token.link() or Token.linkAndExpire()

Expire a Token associated with the current Transaction...

Token.expire()

Stop timing a Segment and have it report as part of its parent Transaction

Segment.end()

Stop timing a Segment and not have it report as part of its parent Transaction

Segment.ignore()

Distributed tracing API usage

These APIs require distributed tracing to be enabled. See Java agent configuration for all distributed tracing config options.

Distributed tracing lets you see the path that a request takes as it travels through a distributed system. For general instructions on how to use the calls below to implement distributed tracing, see Use distributed tracing APIs. To see these APIs in action, see Using Java agent distributing tracing API with Kafka.

Important

With agent version 6.4.0, the following distributed tracing APIs were introduced, with the exception of addCustomAttribute(), which was introduced in 6.1.0. We highly recommended using these APIs instead of the deprecated ones.

If you want to...

Use this

Create and insert distributed tracing headers into a Headers data structure. This API will insert both newrelic and W3C Trace Context headers (traceparent & tracestate), unless the agent is explicitly configured to exclude newrelic headers.

Transaction.insertDistributedTraceHeaders(Headers)

For more on obtaining references to the current transaction and other API classes, see Obtain references.

Accept the distributed tracing headers sent from the calling service and link these services together in a distributed trace.

For more on obtaining references to the current transaction and other API classes, see Obtain references.

The type-specific headers of an inbound or outbound message. For a provided implementation of Headers use ConcurrentHashMapHeaders.

A utility class that provides enum constants for defining the transport type when accepting distributed tracing headers.

Add custom attributes to SpanEvents in distributed traces

NewRelic.getAgent().getTracedMethod().addCustomAttribute(...)

Caution

With agent version 6.4.0, the following distributed tracing APIs have been deprecated and replaced by the APIs in the above table. It's highly recommended to upgrade the agent and use the new APIs instead of these deprecated ones.

If you want to...

Use this

Create a payload to be sent to a called service.

For more on obtaining references to the current transaction and other API classes, see Obtain references.

Caution

API deprecated as of agent 6.4.0

Accept a payload sent from the first service; this will link these services together in a trace.

For more on obtaining references to the current transaction and other API classes, see Obtain references.

Caution

API deprecated as of agent 6.4.0

Payload used to connect services. The text() call returns a JSON string representation of the payload.

DistributedTracePayload.text()

Caution

API deprecated as of agent 6.4.0

Payload used to connect services. The httpSafe() call returns a base64 encoded JSON string representation of the payload.

DistributedTracePayload.httpSafe()

Caution

API deprecated as of agent 6.4.0

Cross application tracing (CAT) API usage

To track external calls and add cross application tracing, use the following APIs:

If you want to...

Use this

Trace across a custom transport channel that New Relic does not support by default, such as a proprietary RPC transport

Also refer to the information in this document about using Transaction to obtain references to New Relic API classes.

View or change the metric name or a rollup metric name of a TracedMethod

(A rollup metric name, such as OtherTransaction/all, is not scoped to a specific transaction. It represents all background transactions.)

Also refer to the information in this document about using TracedMethod to obtain references to New Relic API classes.

Report a call to an external HTTP service, database server, message queue, or other external resource that is being traced using the Java agent API's @Trace annotation

TracedMethod.reportAsExternal(...) passing arguments constructed using ExternalParameters builder.

Also refer to the information in this document about using TracedMethod to obtain references to New Relic API classes.

Enable and add cross application tracing when communicating with an external HTTP or JMS service that is instrumented by New Relic

TracedMethod.addOutboundRequestHeaders(...) along with TracedMethod.reportAsExternal(...)

Also refer to the information in this document about using TracedMethod to obtain references to New Relic API classes.

Add timing for an application server or dispatcher that is not supported automatically

Transaction.setRequest(...), Transaction.setResponse(...), or NewRelic.setRequestAndResponse(...), and Transaction.markResponseSent()

Also refer to the information in this document about using Transaction to obtain references to New Relic API classes.

Obtain references to New Relic API classes

Other tasks require the New Relic Agent object. The Agent object exposes multiple objects that give you the following functionality:

If you want to...

Use this

Get a reference to the current Transaction

NewRelic.getAgent().getTransaction()

Get a Token to link asynchronous work

Start and get a reference to a Segment

Get a reference to the method currently being traced

NewRelic.getAgent().getTracedMethod()

Get a reference to the Agent logger

NewRelic.getAgent().getLogger()

Get a reference to the Agent configuration

NewRelic.getAgent().getConfig()

Get a reference to an aggregator for custom metrics

NewRelic.getAgent().getAggregator()

Get a reference to Insights (our original name for the feature that governed custom events) in order to record custom events

NewRelic.getAgent().getInsights()

Additional API functionality

The following APIs provide additional functionality, such as setting app server info, reporting errors, adding page load timing information, recording custom metrics, and sending custom events.

If you want to...

Use this

Explicitly set port, name, and version information for an application server or dispatcher and the instance name for a JVM

Report an error that New Relic does not report automatically

NewRelic.noticeError(...)

When inside a transaction, the last call to noticeError wins. Only 1 error will be reported per transaction.

Add browser page load timing for Transactions that New Relic does not add to the header automatically

Create and accumulate custom metrics

NewRelic.recordMetric(...), .recordResponseTimeMetric(...), or .incrementCounter(...)

Record custom events

Insights.recordCustomEvent(...)

Or, use NewRelic.addCustomParameter(...) to add custom attributes to the New Relic-defined TransactionEvent type.

Also refer to the information in this document about using Insights to obtain references to New Relic API classes.

Additional API usage examples

For detailed code examples about using the APIs, see New Relic's documentation about custom instrumentation for:

For more help

If you need more help, check out these support and learning resources:

Create issueEdit page
Copyright © 2021 New Relic Inc.