API

new API(agent)

The exported New Relic API. This contains all of the functions meant to be used by New Relic customers.

You do not need to directly instantiate this class, as an instance of this is the return from require('newrelic').

Parameters:
NameTypeDescription
agentobject

Instantiation of lib/agent.js

Methods

addCustomAttribute(key, value) → {false|undefined}

Add a custom attribute to the current transaction and span. Some attributes are reserved (see CUSTOM_DENYLIST for the current, very short list), and as with most API methods, this must be called in the context of an active transaction. Most recently set value wins.

Parameters:
NameTypeDescription
keystring

The key you want displayed in the RPM UI.

valuestring

The value you want displayed. Must be serializable.

Returns:

Returns false when disabled/errored, otherwise undefined

Type: 
false | undefined

addCustomAttributes(attsopt)

Adds all custom attributes in an object to the current transaction and span.

See documentation for newrelic.addCustomAttribute for more information on setting custom attributes.

Parameters:
NameTypeAttributesDescription
attsobject<optional>

Attribute object

Properties
NameTypeAttributesDescription
KEYstring<optional>

The name you want displayed in the RPM UI.

Properties
NameTypeAttributesDescription
VALUEstring<optional>

The value you want displayed. Must be serializable.

Example
newrelic.addCustomAttributes({test: 'value', test2: 'value2'});

addCustomSpanAttribute(key, value) → {false|undefined}

Add a custom span attribute to the current transaction. Some attributes are reserved (see CUSTOM_DENYLIST for the current, very short list), and as with most API methods, this must be called in the context of an active segment/span. Most recently set value wins.

Parameters:
NameTypeDescription
keystring

The key you want displayed in the RPM UI.

valuestring

The value you want displayed. Must be serializable.

Returns:

Returns false when disabled/errored, otherwise undefined

Type: 
false | undefined

addCustomSpanAttributes(attsopt)

Add custom span attributes in an object to the current segment/span.

See documentation for newrelic.addCustomSpanAttribute for more information.

Parameters:
NameTypeAttributesDescription
attsobject<optional>

Attribute object

Properties
NameTypeAttributesDescription
KEYstring<optional>

The name you want displayed in the RPM UI.API.

Properties
NameTypeAttributesDescription
VALUEstring<optional>

The value you want displayed. Must be serializable.

Example
newrelic.addCustomSpanAttribute({test: 'value', test2: 'value2'})

addIgnoringRule(pattern) → {void}

If the URL for a transaction matches the provided pattern, ignore the transaction attached to that URL. Useful for filtering socket.io connections and other long-polling requests out of your agents to keep them from distorting an app's apdex or mean response time. Pattern may be a (standard JavaScript) RegExp or a string.

Parameters:
NameTypeDescription
patternRegExp

The pattern to ignore.

Returns:
Type: 
void
Example
newrelic.addIgnoringRule('^/socket\\.io/')

addNamingRule(pattern, name) → {void}

If the URL for a transaction matches the provided pattern, name the transaction with the provided name. If there are capture groups in the pattern (which is a standard JavaScript regular expression, and can be passed as either a RegExp or a string), then the substring matches ($1, $2, etc.) are replaced in the name string. BE CAREFUL WHEN USING SUBSTITUTION. If the replacement substrings are highly variable (i.e. are identifiers, GUIDs, or timestamps), the rule will generate too many metrics and potentially get your application blocked by New Relic.

Parameters:
NameTypeDescription
patternRegExp

The pattern to rename (with capture groups).

namestring

The name to use for the transaction.

Returns:
Type: 
void
Examples
// An example of a good rule with replacements:
newrelic.addNamingRule('^/storefront/(v[1-5])/(item|category|tag)',
                       'CommerceAPI/$1/$2')
// An example of a bad rule with replacements:
newrelic.addNamingRule('^/item/([0-9a-f]+)', 'Item/$1')

// Keep in mind that the original URL and any query parameters will be sent
// along with the request, so slow transactions will still be identifiable.

// Naming rules can not be removed once added. They can also be added via the
// agent's configuration. See configuration documentation for details.

endTransaction()

End the current web or background custom transaction. This method requires being in the correct transaction context when called.

getBrowserTimingHeader(options) → {string}

Get the script header necessary for Browser Monitoring This script must be manually injected into your templates, as high as possible in the header, but after any X-UA-COMPATIBLE HTTP-EQUIV meta tags. Otherwise you may hurt IE!

By default this method will return a script wrapped by <script> tags, but with option hasToRemoveScriptWrapper it can send back only the script content without the <script> wrapper. Useful for React component based frontend.

This method must be called every time you want to generate the headers.

Do not reuse the headers between users, or even between requests.

Parameters:
NameTypeDescription
optionsobject

configuration options

Properties
NameTypeAttributesDescription
noncestring<optional>

Nonce to inject into <script> header.

hasToRemoveScriptWrapperboolean<optional>

Used to import agent script without <script> tag wrapper.

allowTransactionlessInjectionoptions<optional>

Whether or not to allow the Browser Agent to be injected when there is no active transaction

Returns:

The script content to be injected in <head> or put inside <script> tag (depending on options)

Type: 
string

getLinkingMetadata(omitSupportability) → {object}

This method returns an object with the following keys/data:

  • trace.id: The current trace ID
  • span.id: The current span ID
  • entity.name: The application name specified in the connect request as app_name. If multiple application names are specified this will only be the first name
  • entity.type: The string "SERVICE"
  • entity.guid: The entity ID returned in the connect reply as entity_guid
  • hostname: The hostname as specified in the connect request as utilization.full_hostname. If utilization.full_hostname is null or empty, this will be the hostname specified in the connect request as host.
Parameters:
NameTypeDescription
omitSupportabilityboolean

Whether or not to log the supportability metric, true means skip

Returns:

The LinkingMetadata object with the data above

Type: 
object

getTraceMetadata() → {*}

Returns the current trace and span id.

Returns:

The object containing the current trace and span ids

Type: 
*

getTransaction() → {TransactionHandle}

This method returns an object with the following methods:

  • end: end the transaction that was active when API#getTransaction was called.

  • ignore: set the transaction that was active when API#getTransaction was called to be ignored.

Returns:

The transaction object with the end and ignore methods on it.

Type: 
TransactionHandle

ignoreApdex()

Ignores the current transaction when calculating your Apdex score. This is useful when you have either very short or very long transactions (such as file downloads) that can skew your Apdex score.

incrementMetric(name, valueopt)

Create or update a custom metric that acts as a simple counter. The count of the given metric will be incremented by the specified amount, defaulting to 1.

Parameters:
NameTypeAttributesDescription
namestring

The name of the metric.

valuenumber<optional>

The amount that the count of the metric should be incremented by. Defaults to 1.

instrument(moduleName, onRequire, onError)

Registers an instrumentation function.

  • newrelic.instrument(moduleName, onRequire [,onError])
  • newrelic.instrument(options)
Parameters:
NameTypeDescription
moduleNamestring | object

The module name given to require to load the module, or the instrumentation specification

Properties
NameTypeAttributesDescription
moduleNamestring

The module name given to require to load the module

absolutePathstring<optional>

Must provide absolute path to module if it does not exist within node_modules. This is used to instrument a file within the same application.

onRequirefunction

The function to call when the module has been loaded

onErrorfunction<optional>

If provided, should onRequire throw an error, the error will be passed to

onRequirefunction

The function to call when the module has been loaded

onErrorfunction

If provided, should onRequire throw an error, the error will be passed to this function.

instrumentConglomerate(moduleName, onRequire, onError)

Registers an instrumentation function.

  • newrelic.instrumentConglomerate(moduleName, onRequire [, onError])
  • newrelic.instrumentConglomerate(options)
Parameters:
NameTypeDescription
moduleNamestring | object

The module name given to require to load the module, or the instrumentation specification

Properties
NameTypeAttributesDescription
moduleNamestring

The module name given to require to load the module

absolutePathstring<optional>

Must provide absolute path to module if it does not exist within node_modules. This is used to instrument a file within the same application.

onRequirefunction

The function to call when the module has been loaded

onErrorfunction<optional>

If provided, should onRequire throw an error, the error will be passed to

onRequirefunction

The function to call when the module has been loaded

onErrorfunction

If provided, should onRequire throw an error, the error will be passed to this function.

instrumentDatastore(moduleName, onRequire, onError)

Registers an instrumentation function.

  • newrelic.instrumentDatastore(moduleName, onRequire [,onError])
  • newrelic.instrumentDatastore(options)
Parameters:
NameTypeDescription
moduleNamestring | object

The module name given to require to load the module, or the instrumentation specification

Properties
NameTypeAttributesDescription
moduleNamestring

The module name given to require to load the module

absolutePathstring<optional>

Must provide absolute path to module if it does not exist within node_modules. This is used to instrument a file within the same application.

onRequirefunction

The function to call when the module has been loaded

onErrorfunction<optional>

If provided, should onRequire throw an error, the error will be passed to

onRequirefunction

The function to call when the module has been loaded

onErrorfunction

If provided, should onRequire throw an error, the error will be passed to this function.

instrumentLoadedModule(moduleName, module) → {boolean}

Applies an instrumentation to an already loaded CommonJs module.

Note: This function will not work for ESM packages.

Parameters:
NameTypeDescription
moduleNamestring

The module's name/identifier. Will be normalized into an instrumentation key.

moduleobject

The actual module object or function we're instrumenting

Returns:

Whether or not the module was successfully instrumented

Type: 
boolean
Example
// oh no, express was loaded before newrelic
const express   = require('express')
const newrelic  = require('newrelic')

// phew, we can use instrumentLoadedModule to make
// sure express is still instrumented
newrelic.instrumentLoadedModule('express', express)

instrumentMessages(moduleName, onRequire, onError)

Registers an instrumentation function for instrumenting message brokers.

  • newrelic.instrumentMessages(moduleName, onRequire [,onError])
  • newrelic.instrumentMessages(options)
Parameters:
NameTypeDescription
moduleNamestring | object

The module name given to require to load the module, or the instrumentation specification

Properties
NameTypeAttributesDescription
moduleNamestring

The module name given to require to load the module

absolutePathstring<optional>

Must provide absolute path to module if it does not exist within node_modules. This is used to instrument a file within the same application.

onRequirefunction

The function to call when the module has been loaded

onErrorfunction<optional>

If provided, should onRequire throw an error, the error will be passed to

onRequirefunction

The function to call when the module has been loaded

onErrorfunction

If provided, should onRequire throw an error, the error will be passed to this function.

instrumentWebframework(moduleName, onRequire, onError)

Registers an instrumentation function.

  • newrelic.instrumentWebframework(moduleName, onRequire [,onError])
  • newrelic.instrumentWebframework(options)
Parameters:
NameTypeDescription
moduleNamestring | object

The module name given to require to load the module, or the instrumentation specification

Properties
NameTypeAttributesDescription
moduleNamestring

The module name given to require to load the module

absolutePathstring<optional>

Must provide absolute path to module if it does not exist within node_modules. This is used to instrument a file within the same application.

onRequirefunction

The function to call when the module has been loaded

onErrorfunction<optional>

If provided, should onRequire throw an error, the error will be passed to

onRequirefunction

The function to call when the module has been loaded

onErrorfunction

If provided, should onRequire throw an error, the error will be passed to this function.

noticeError(error, customAttributesopt, expected) → {false|undefined}

Send errors to New Relic that you've already handled yourself. Should be an Error or one of its subtypes, but the API will handle strings and objects that have an attached .message or .stack property.

NOTE: Errors that are recorded using this method do not obey the ignore_status_codes configuration.

Parameters:
NameTypeAttributesDescription
errorError

The error to be traced.

customAttributesobject<optional>

Optional. Any custom attributes to be displayed in the New Relic UI.

expectedboolean

Optional. False by default. True if the error is expected, meaning it should be collected for error events and traces, but should not impact error rate.

Returns:

Returns false when disabled/errored, otherwise undefined

Type: 
false | undefined
Example
try {
 performSomeTask();
} catch (err) {
 newrelic.noticeError(
   err,
   {extraInformation: "error already handled in the application"},
   true
 );
}

obfuscateSql(sql, dialect) → {string}

Obfuscates SQL for a given database engine.

Parameters:
NameTypeDescription
sqlstring

sql statement

dialectstring

engine of the sql (mysql, postgres, cassandra, oracle)

Returns:

sql that obfuscates raw values

Type: 
string

recordCustomEvent(eventType, attributes) → {false|undefined}

Record custom event data which can be queried in New Relic Insights.

Parameters:
NameTypeDescription
eventTypestring

The name of the event. It must be an alphanumeric string less than 255 characters.

attributesobject

Object of key and value pairs. The keys must be shorter than 255 characters, and the values must be string, number, or boolean.

Returns:

Returns false explicitly if failed/disabled, otherwise undefined

Type: 
false | undefined

recordLlmFeedbackEvent(params)

Record a LLM feedback event which can be viewed in New Relic API Monitoring.

Parameters:
NameTypeDescription
paramsobject

Input parameters.

Properties
NameTypeAttributesDescription
traceIdstring

Identifier for the feedback event. Obtained from getTraceMetadata.

categorystring

A tag for the event.

ratingstring

A indicator of how useful the message was.

messagestring<optional>

The message that triggered the event.

metadataobject<optional>

Additional key-value pairs to associate with the recorded event.

recordLogEvent(logEvent)

Sends an application log message to New Relic. The agent already automatically does this for some instrumented logging libraries, but in case you are using another logging method that is not already instrumented by the agent, you can use this function instead.

If application log forwarding is disabled in the agent configuration, this function does nothing.

Parameters:
NameTypeDescription
logEventobject

The log event object to send. Any attributes besides message, level, timestamp, and error are recorded unchanged. The logEvent object itself will be mutated by this function.

Properties
NameTypeDescription
messagestring

The log message.

levelstring

The log level severity. If this key is missing, it will default to UNKNOWN

timestampnumber

ECMAScript epoch number denoting the time that this log message was produced. If this key is missing, it will default to the output of Date.now().

errorError

Error associated to this log event. Ignored if missing.

Example
newrelic.recordLogEvent({
 message: 'cannot find file',
 level: 'ERROR',
 error: new SystemError('missing.txt')
})

recordMetric(name, value)

Record a custom metric, usually associated with a particular duration. The name must be a string following standard metric naming rules. The value will usually be a number, but it can also be an object. When value is a numeric value, it should represent the magnitude of a measurement associated with an event; for example, the duration for a particular method call. When value is an object, it must contain count, total, min, max, and sumOfSquares keys, all with number values. This form is useful to aggregate metrics on your own and report them periodically; for example, from a setInterval. These values will be aggregated with any previously collected values for the same metric. The names of these keys match the names of the keys used by the platform API.

Parameters:
NameTypeDescription
namestring

The name of the metric.

valuenumber | object

The value of the metric to record

setControllerName(name, action) → {void}

Give the current transaction a name based on your own idea of what constitutes a controller in your Node application. Also allows you to optionally specify the action being invoked on the controller. If the action is omitted, then the API will default to using the HTTP method used in the request (e.g. GET, POST, DELETE). Overrides any New Relic naming rules set in configuration or from New Relic's servers.

IMPORTANT: this function must be called when a transaction is active. New Relic transactions are tied to web requests, so this method may be called from within HTTP or HTTPS listener functions, Express routes, or other contexts where a web request or response object are in scope.

Parameters:
NameTypeDescription
namestring

The name you want to give the controller in the New Relic UI. Will be prefixed with 'Controller/' when sent.

actionstring

The action being invoked on the controller. Defaults to the HTTP method used for the request.

Returns:
Type: 
void

setDispatcher(name, versionopt)

Specify the Dispatcher and Dispatcher Version environment values. A dispatcher is typically the service responsible for brokering the request with the process responsible for responding to the request. For example Node's http module would be the dispatcher for incoming HTTP requests.

Parameters:
NameTypeAttributesDescription
namestring

The string you would like to report to New Relic as the dispatcher.

versionstring<optional>

The dispatcher version you would like to report to New Relic

setErrorGroupCallback(callback)

Function for adding a custom callback to generate Error Group names, which will be used by the Errors Inbox to group similar errors together via the error.group.name agent attribute.

Provided functions must return a string, and receive an object as an argument, which contains information related to the Error that occurred, and has the following format:

{
  customAttributes: object,
  'request.uri': string,
  'http.statusCode': string,
  'http.method': string,
  error: Error,
  'error.expected': boolean
}

Calling this function multiple times will replace previously defined functions

Parameters:
NameTypeDescription
callbackfunction

callback function to generate error.group.name attribute

Example
function myCallback(metadata) {
  if (metadata['http.statusCode'] === '400') {
    return 'Bad User Input'
  }
}
newrelic.setErrorGroupCallback(myCallback)

setLlmTokenCountCallback(callback)

Registers a callback which will be used for calculating token counts on Llm events when they are not available. This function will typically only be used if ai_monitoring.record_content.enabled is false and you want to still capture token counts for Llm events.

Provided callbacks must return an integer value for the token count for a given piece of content.

Parameters:
NameTypeDescription
callbackfunction

synchronous function called to calculate token count for content.

Example
// @param {string} model - name of model (i.e. gpt-3.5-turbo)
// @param {string} content - prompt or completion response
function tokenCallback(model, content) {
 // calculate tokens based on model and content
 // return token count
 return 40
}

setTransactionName(name) → {void}

Give the current transaction a custom name. Overrides any New Relic naming rules set in configuration or from New Relic's servers.

IMPORTANT: this function must be called when a transaction is active. New Relic transactions are tied to web requests, so this method may be called from within HTTP or HTTPS listener functions, Express routes, or other contexts where a web request or response object are in scope.

Parameters:
NameTypeDescription
namestring

The name you want to give the web request in the New Relic UI. Will be prefixed with 'Custom/' when sent.

Returns:
Type: 
void

setUserID(id)

Assigns enduser.id attribute on transaction and trace events. It will also assign the attribute to errors if they occur within a transaction.

Parameters:
NameTypeDescription
idstring

a unique identifier used to set the enduser.id attribute

shutdown(optionsopt, cbopt)

Shuts down the agent.

Parameters:
NameTypeAttributesDescription
optionsobject<optional>

Object with shut down options.

Properties
NameTypeAttributesDescription
collectPendingDataboolean<optional>

If true, the agent will send any pending data to the collector before shutting down.

timeoutnumber<optional>

Time in milliseconds to wait before shutting down.

waitForIdleboolean<optional>

If true, the agent will not shut down until there are no active transactions.

cbfunction<optional>

Callback function that runs when agent stops.

startBackgroundTransaction(name, groupopt, handle) → {null|*}

Creates and starts a background transaction to record work done in the handle supplied. This transaction will run until the handle synchronously returns UNLESS:

  1. The handle function returns a promise, where the end of the transaction will be tied to the end of the promise returned.
  2. API#getTransaction is called in the handle, flagging the transaction as externally handled. In this case the transaction will be ended when TransactionHandle#end is called in the user's code.
Parameters:
NameTypeAttributesDescription
namestring

The name of the transaction. It is used to name and group related transactions in APM, so it should be a generic name and not include any variable parameters.

groupstring<optional>

Optional, used for grouping background transactions in APM. For more information see: https://docs.newrelic.com/docs/apm/applications-menu/monitoring/transactions-page#txn-type-dropdown

handlefunction

Function that represents the background work.

Returns:

Returns null if handle is not a function, otherwise the return value of handle

Type: 
null | *
Example
const newrelic = require('newrelic')
newrelic.startBackgroundTransaction('Red October', 'Subs', function() {
  const transaction = newrelic.getTransaction()
  setTimeout(function() {
    // do some work
    transaction.end()
  }, 100)
})

startSegment(name, record, handler, callbackopt) → {*}

Wraps the given handler in a segment which may optionally be turned into a metric.

Parameters:
NameTypeAttributesDescription
namestring

The name to give the new segment. This will also be the name of the metric.

recordboolean

Indicates if the segment should be recorded as a metric. Metrics will show up on the transaction breakdown table and server breakdown graph. Segments just show up in transaction traces.

handlerstartSegmentCallback

The function to track as a segment.

callbackfunction<optional>

An optional callback for the handler. This will indicate the end of the timing if provided.

Returns:

Returns the result of calling handler.

Type: 
*
Example
newrelic.startSegment('mySegment', false, function handler() {
   // The returned promise here will signify the end of the segment.
   return myAsyncTask().then(myNextTask)
 })

startWebTransaction(url, handle) → {null|*}

Creates and starts a web transaction to record work done in the handle supplied. This transaction will run until the handle synchronously returns UNLESS:

  1. The handle function returns a promise, where the end of the transaction will be tied to the end of the promise returned.
  2. API#getTransaction is called in the handle, flagging the transaction as externally handled. In this case the transaction will be ended when TransactionHandle#end is called in the user's code.
Parameters:
NameTypeDescription
urlstring

The URL of the transaction. It is used to name and group related transactions in APM, so it should be a generic name and not include any variable parameters.

handlefunction

Function that represents the transaction work.

Returns:

Returns null if handle is not a function, otherwise the return value of handle

Type: 
null | *
Example
const newrelic = require('newrelic')
newrelic.startWebTransaction('/some/url/path', function() {
  const transaction = newrelic.getTransaction()
  setTimeout(function() {
    // do some work
    transaction.end()
  }, 100)
})

withLlmCustomAttributes(context, callback)

Run a function with the passed in LLM context as the active context and return its return value.

Parameters:
NameTypeDescription
contextObject

LLM custom attributes context

callbackfunction

The function to execute in context.

Example
const OpenAI = require('openai')
const client = new OpenAI()
newrelic.withLlmCustomAttributes({'llm.someAttribute': 'someValue'}, async () => {
   const response = await client.chat.completions.create({ messages: [
     { role: 'user', content: 'Tell me about Node.js.'}
   ]})
})