Guide to using the Java agent API

The New Relic Java agent API lets you control, customize, and extend the functionality of the New Relic 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.

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 3.36.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.
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()

Trace calls to external services

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

Transaction.getRequestMetadata(), .processRequestMetadata(...), .getResponseMetadata(), .processResponseMetadata(...)

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

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

TracedMethod.getMetricName(), .setMetricName(...), .setRollupMetricName(...)

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

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

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

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

Obtain references to New Relic entities

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
NewRelic.getAgent().getTransaction().getToken()
Start and get a reference to a Segment
NewRelic.getAgent().getTransaction().startSegment()
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 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 to Insights.

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
NewRelic.setAppServerPort(...), .setServerInfo(...), and .setInstanceName(...)
Report an error that New Relic does not report automatically NewRelic.noticeError(...)
Add browser page load timing for Transactions that New Relic does not add to the header automatically
NewRelic.getBrowserTimingHeader(), .getBrowserTimingFooter(), .setUserName(String name), .setAccountName(String name), and .setProductName(String name)
Create and accumulate custom metrics NewRelic.recordMetric(...), .recordResponseTimeMetric(...), or .incrementCounter(...)

Record Insights 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 entities.

Additional API usage examples

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

For more help

Recommendations for learning more: