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')
.
Name | Type | Description |
---|---|---|
agent | object | 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.
Name | Type | Description |
---|---|---|
key | string | The key you want displayed in the RPM UI. |
value | string | The value you want displayed. Must be serializable. |
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.
Name | Type | Attributes | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
atts | object | <optional> | Attribute object Properties
|
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.
Name | Type | Description |
---|---|---|
key | string | The key you want displayed in the RPM UI. |
value | string | The value you want displayed. Must be serializable. |
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.
Name | Type | Attributes | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
atts | object | <optional> | Attribute object Properties
|
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.
Name | Type | Description |
---|---|---|
pattern | RegExp | The pattern to ignore. |
- Type:
- void
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.
Name | Type | Description |
---|---|---|
pattern | RegExp | The pattern to rename (with capture groups). |
name | string | The name to use for the transaction. |
- Type:
- void
// 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.
Name | Type | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options | object | configuration options Properties
|
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 IDspan.id
: The current span IDentity.name
: The application name specified in the connect request as app_name. If multiple application names are specified this will only be the first nameentity.type
: The string "SERVICE"entity.guid
: The entity ID returned in the connect reply as entity_guidhostname
: 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.
Name | Type | Description |
---|---|---|
omitSupportability | boolean | Whether or not to log the supportability metric, true means skip |
The LinkingMetadata object with the data above
- Type:
- object
getTraceMetadata() → {*}
Returns the current trace and span id.
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.
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.
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. Defaults to 1. |
instrument(moduleName, onRequire, onError)
Registers an instrumentation function.
newrelic.instrument(moduleName, onRequire [,onError])
newrelic.instrument(options)
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
moduleName | string | | The module name given to require to load the module, or the instrumentation specification Properties
| ||||||||||||||||||||
onRequire | function | The function to call when the module has been loaded | ||||||||||||||||||||
onError | function | If provided, should |
instrumentConglomerate(moduleName, onRequire, onError)
Registers an instrumentation function.
newrelic.instrumentConglomerate(moduleName, onRequire [, onError])
newrelic.instrumentConglomerate(options)
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
moduleName | string | | The module name given to require to load the module, or the instrumentation specification Properties
| ||||||||||||||||||||
onRequire | function | The function to call when the module has been loaded | ||||||||||||||||||||
onError | function | If provided, should |
instrumentDatastore(moduleName, onRequire, onError)
Registers an instrumentation function.
newrelic.instrumentDatastore(moduleName, onRequire [,onError])
newrelic.instrumentDatastore(options)
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
moduleName | string | | The module name given to require to load the module, or the instrumentation specification Properties
| ||||||||||||||||||||
onRequire | function | The function to call when the module has been loaded | ||||||||||||||||||||
onError | function | If provided, should |
instrumentLoadedModule(moduleName, module) → {boolean}
Applies an instrumentation to an already loaded CommonJs module.
Note: This function will not work for ESM packages.
Name | Type | Description |
---|---|---|
moduleName | string | The module's name/identifier. Will be normalized into an instrumentation key. |
module | object | The actual module object or function we're instrumenting |
Whether or not the module was successfully instrumented
- Type:
- boolean
// 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)
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
moduleName | string | | The module name given to require to load the module, or the instrumentation specification Properties
| ||||||||||||||||||||
onRequire | function | The function to call when the module has been loaded | ||||||||||||||||||||
onError | function | If provided, should |
instrumentWebframework(moduleName, onRequire, onError)
Registers an instrumentation function.
newrelic.instrumentWebframework(moduleName, onRequire [,onError])
newrelic.instrumentWebframework(options)
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
moduleName | string | | The module name given to require to load the module, or the instrumentation specification Properties
| ||||||||||||||||||||
onRequire | function | The function to call when the module has been loaded | ||||||||||||||||||||
onError | function | If provided, should |
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.
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. |
expected | boolean | 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 false when disabled/errored, otherwise undefined
- Type:
- false |
undefined
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.
Name | Type | Description |
---|---|---|
sql | string | sql statement |
dialect | string | engine of the sql (mysql, postgres, cassandra, oracle) |
sql that obfuscates raw values
- Type:
- string
recordCustomEvent(eventType, attributes) → {false|undefined}
Record custom event data which can be queried in New Relic Insights.
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. |
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.
Name | Type | Description | ||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
params | object | Input parameters. Properties
|
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.
Name | Type | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
logEvent | object | The log event object to send. Any attributes besides Properties
|
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.
Name | Type | Description |
---|---|---|
name | string | The name of the metric. |
value | number | | 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.
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. |
- 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.
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 |
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
Name | Type | Description |
---|---|---|
callback | function | callback function to generate |
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.
Name | Type | Description |
---|---|---|
callback | function | synchronous function called to calculate token count for content. |
// @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.
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. |
- 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.
Name | Type | Description |
---|---|---|
id | string | a unique identifier used to set the |
shutdown(optionsopt, cbopt)
Shuts down the agent.
Name | Type | Attributes | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options | object | <optional> | Object with shut down options. Properties
| ||||||||||||||||
cb | function | <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:
- The handle function returns a promise, where the end of the transaction will be tied to the end of the promise returned.
API#getTransaction
is called in the handle, flagging the transaction as externally handled. In this case the transaction will be ended whenTransactionHandle#end
is called in the user's code.
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 include 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 null if handle is not a function, otherwise the return value of handle
- Type:
- null |
*
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.
Name | Type | Attributes | Description |
---|---|---|---|
name | string | The name to give the new segment. This will also be the name of the metric. | |
record | boolean | 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 the result of calling handler
.
- Type:
- *
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:
- The handle function returns a promise, where the end of the transaction will be tied to the end of the promise returned.
API#getTransaction
is called in the handle, flagging the transaction as externally handled. In this case the transaction will be ended whenTransactionHandle#end
is called in the user's code.
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 include any variable parameters. |
handle | function | Function that represents the transaction work. |
Returns null if handle is not a function, otherwise the return value of handle
- Type:
- null |
*
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.
Name | Type | Description |
---|---|---|
context | Object | LLM custom attributes context |
callback | function | The function to execute in context. |
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.'}
]})
})