• /
  • EnglishEspañol日本語한국어Português
  • EntrarComeçar agora

Guide to using the Java agent API

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

Importante

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, download it from maven central via a build tool.

Here's an example for gradle where you can replace ${agent.version} with version of your agent:

implementation 'com.newrelic.agent.java:newrelic-api:${agent.version}'

You can call the API even without the agent running, but the methods will be a no-op until the agent loads your application.

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

Adds user tracking to Transactions by setting the enduser.id agent attribute.

NewRelic.setUserId()

Prevent a Transaction from being reported to New Relic

NewRelic.ignoreTransaction()

Exclude a Transaction when calculating your app's Apdex score

NewRelic.ignoreApdex()

See related logs

To see logs directly within the context of your application's errors and traces, use these API calls to annotate your logs:

For more information about correlating log data with other telemetry data, see our logs in context documentation.

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.

Importante

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

Learn about the type-specific headers of an inbound or outbound message.

Headers

For a provided implementation of Headers use ConcurrentHashMapHeaders.

See an example of W3C trace context headers implementation in DT API usage with Kafka.

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.

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.

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

Cuidado

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.

Cuidado

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.

Cuidado

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

Cuidado

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

Cuidado

API deprecated as of agent 6.4.0

Cross application tracing (CAT) API usage

Importante

Cross application tracing has been deprecated as of agent version 7.4.0 and will be removed in a future agent version.

Instead of using cross application tracing, we recommend our distributed tracing features. Distributed tracing is an improvement on the cross application tracing feature and is recommended for large, distributed systems.

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.

Group errors with your own custom defined fingerprint, implement the ErrorGroupCallback interface are used to generate grouping keys for errors that will be sent to New Relic. The fingerprint will be used to group error messages in the Errors Inbox UI.

public interface ErrorGroupCallback { String generateGroupingString(ErrorData errorData); }

Set your own error fingerprint via a callback function. To register an ErrorGroupCallback that's used to generate a grouping key for the supplied error.

NewRelic.setErrorGroupCallback(errorGroupCallback)

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.

Provide general cloud provider account information to the agent

NewRelic.getAgent().getCloud().setAccountInfo(CloudAccountInfo.AWS_ACCOUNT_ID, "...");

With this method, you can provide the type of account information and its value. The agent uses this information to populate the attribute cloud.resource_id in the select cloud services spans.

AWS DynamoDB and Kinesis are services that require this value to populate the cloud.resource_id attribute. Similarly, AWS Lambda requires this value when the account ID is not part of the function name.

Calling this method overrides the respective cloud configuration. The call shown above overrides cloud.aws.account_id.

Provide SDK client specific cloud provider account information to the agent

NewRelic.getAgent().getCloud().setAccountInfo(sdkClient, CloudAccountInfo.AWS_ACCOUNT_ID, "...");

This call provides the same information as the preceding method, but it is specific to the SDK client provided. When the specified SDK client is used, this data will be used instead of the general one.

Additional API usage examples

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

Copyright © 2024 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.