API

API

new API()

The exported New Relic API. This contains all of the functions meant to be used by New Relic customers. For now, that means transaction naming.

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

Source:

Members

addCustomParameter

Deprecated. Please use addCustomAttribute instead. TODO: remove in v5

Source:

addCustomParameters

Deprecated. Please use addCustomAttributes instead. TODO: remove in v5

Source:

Methods

addCustomAttribute(key, value)

Add a custom attribute to the current transaction. Some attributes are reserved (see CUSTOM_BLACKLIST 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.

Source:
Parameters:
Name Type Description
key string

The key you want displayed in the RPM UI.

value string

The value you want displayed. Must be serializable.

addCustomAttributes(attsopt)

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

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

An example of setting a custom attribute object:

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

Source:
Parameters:
Name Type Attributes Description
atts object <optional>
Name Type Attributes Description
KEY string <optional>

The name you want displayed in the RPM UI.

Name Type Attributes Description
VALUE string <optional>

The value you want displayed. Must be serializable.

addIgnoringRule(pattern)

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.

Example:

newrelic.addIgnoringRule('^/socket\.io/')

Source:
Parameters:
Name Type Description
pattern RegExp

The pattern to ignore.

addNamingRule(pattern, name)

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 blacklisted by New Relic.

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.

Source:
Parameters:
Name Type Description
pattern RegExp

The pattern to rename (with capture groups).

name string

The name to use for the transaction.

createBackgroundTransaction(name, groupopt, handle) → {function}

Creates a function that represents a background transaction. It does not start the transaction automatically - the returned function needs to be invoked to start it. Inside the handler function, the transaction must be ended by calling endTransaction().

Deprecated:
  • since version 2.0
Source:
Parameters:
Name Type Attributes Description
name string

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 iclude any variable parameters.

group string <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

handle function

Function that represents the background work.

Returns:
Type:
function

The handle function wrapped with starting a new transaction. This function can be called repeatedly to start multiple transactions.

Example
var newrelic = require('newrelic')
 var startTx = newrelic.createBackgroundTransaction('myTransaction', function(a, b) {
   // Do some work
   newrelic.endTransaction()
 })
 startTx('a', 'b') // Start the transaction.

createTracer()

This creates a new tracer with the passed in name. It then wraps the callback and binds it to the current transaction and segment so any further custom instrumentation as well as auto instrumentation will also be able to find the current transaction and segment.

Deprecated:
Source:

createWebTransaction(url, handle)

Creates a function that represents a web transaction. It does not start the transaction automatically - the returned function needs to be invoked to start it. Inside the handler function, the transaction must be ended by calling endTransaction().

Deprecated:
  • since version 2.0
Source:
Parameters:
Name Type Description
url string

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 iclude any variable parameters.

handle function

Function that represents the transaction work.

Example
var newrelic = require('newrelic')
var transaction = newrelic.createWebTransaction('/some/url/path', function() {
  // do some work
  newrelic.endTransaction()
})

endTransaction()

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

Source:

getBrowserTimingHeader() → {string}

Get the 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!

This method must be called during a transaction, and must be called every time you want to generate the headers.

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

Source:
Parameters:
Name Type Attributes Description
options.nonce string <optional>

Nonce to inject into <script> header.

Returns:
Type:
string

The <script> header to be injected.

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.

Source:
Returns:
Type:
TransactionHandle

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

incrementMetric(name, valueopt)

Update a metric that acts as a simple counter. The count of the selected metric will be incremented by the specified amount, defaulting to 1.

Source:
Parameters:
Name Type Attributes Description
name string

The name of the metric.

value number <optional>

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

instrument(options)

Registers an instrumentation function.

  • newrelic.instrument(moduleName, onRequire [,onError])
  • newrelic.instrument(options)
Source:
Parameters:
Name Type Description
options object

The options for this custom instrumentation.

Name Type Attributes Description
moduleName string

The module name given to require to load the module

onRequire function

The function to call when the module is required

onError function <optional>

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

instrumentDatastore(options)

Registers an instrumentation function.

  • newrelic.instrumentDatastore(moduleName, onRequire [,onError])
  • newrelic.instrumentDatastore(options)
Source:
Parameters:
Name Type Description
options object

The options for this custom instrumentation.

Name Type Attributes Description
moduleName string

The module name given to require to load the module

onRequire function

The function to call when the module is required

onError function <optional>

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

instrumentMessages(options)

Registers an instrumentation function for instrumenting message brokers.

  • newrelic.instrumentMessages(moduleName, onRequire [,onError])
  • newrelic.instrumentMessages(options)
Source:
Parameters:
Name Type Description
options object

The options for this custom instrumentation.

Name Type Attributes Description
moduleName string

The module name given to require to load the module

onRequire function

The function to call when the module is required

onError function <optional>

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

instrumentWebframework(options)

Registers an instrumentation function.

  • newrelic.instrumentWebframework(moduleName, onRequire [,onError])
  • newrelic.instrumentWebframework(options)
Source:
Parameters:
Name Type Description
options object

The options for this custom instrumentation.

Name Type Attributes Description
moduleName string

The module name given to require to load the module

onRequire function

The function to call when the module is required

onError function <optional>

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

noticeError(error, customAttributesopt)

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.

Source:
Parameters:
Name Type Attributes Description
error Error

The error to be traced.

customAttributes object <optional>

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

recordCustomEvent(eventType, attributes)

Record an event-based metric, usually associated with a particular duration.

Source:
Parameters:
Name Type Description
eventType string

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

attributes object

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

recordMetric(name, value)

Record an event-based 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.
Source:
Parameters:
Name Type Description
name string

The name of the metric.

value number | object

setControllerName(name, action)

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.

Source:
Parameters:
Name Type Description
name string

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

action string

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

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.

Source:
Parameters:
Name Type Attributes Description
name string

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

version string <optional>

The dispatcher version you would like to report to New Relic

setIgnoreTransaction(ignored)

Tell the tracer whether to ignore the current transaction. The most common use for this will be to mark a transaction as ignored (maybe it's handling a websocket polling channel, or maybe it's an external call you don't care is slow), but it's also useful when you want a transaction that would otherwise be ignored due to URL or transaction name normalization rules to not be ignored.

Source:
Parameters:
Name Type Description
ignored boolean

Ignore, or don't ignore, the current transaction.

setTransactionName(name)

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.

Source:
Parameters:
Name Type Description
name string

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

shutdown(optionsopt, callbackopt)

Shuts down the agent.

Source:
Parameters:
Name Type Attributes Description
options object <optional>

object with shut down options

Name Type Attributes Default Description
collectPendingData boolean <optional>
false

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

timeout number <optional>

time in ms to wait before shutting down

callback function <optional>

callback function that runs when agent stopped

startBackgroundTransaction(name, groupopt, handle)

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.
Source:
Parameters:
Name Type Attributes Description
name string

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 iclude any variable parameters.

group string <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

handle function

Function that represents the background work.

Example
var newrelic = require('newrelic')
newrelic.startBackgroundTransaction('Red October', 'Subs', function() {
  var 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.

Source:
Parameters:
Name Type Attributes Description
name string

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

record bool

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.

handler startSegmentCallback

The function to track as a segment.

callback function <optional>

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

Returns:
Type:
*

Returns the result of calling handler.

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)

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.
Source:
Parameters:
Name Type Description
url string

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 iclude any variable parameters.

handle function

Function that represents the transaction work.

Example
var newrelic = require('newrelic')
newrelic.startWebTransaction('/some/url/path', function() {
  var transaction = newrelic.getTransaction()
  setTimeout(function() {
    // do some work
    transaction.end()
  }, 100)
})