diff --git a/src/content/docs/apm/agents/nodejs-agent/api-guides/guide-using-nodejs-agent-api.mdx b/src/content/docs/apm/agents/nodejs-agent/api-guides/guide-using-nodejs-agent-api.mdx index f2fd9ff6c41..ced76a596e9 100644 --- a/src/content/docs/apm/agents/nodejs-agent/api-guides/guide-using-nodejs-agent-api.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/api-guides/guide-using-nodejs-agent-api.mdx @@ -19,9 +19,9 @@ You can also use the API for [custom instrumentation](/docs/agents/nodejs-agent/ Other resources: -* The [Node.js agent API documentation on GitHub](http://newrelic.github.io/node-newrelic/) has more detail and practical tutorials. +* The [Node.js agent API documentation on GitHub](https://newrelic.github.io/node-newrelic/API.html). +* [Example applications using custom instrumentation](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation). * You can also adjust the Node.js agent's default behavior with [configuration settings](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration). -* To see all available New Relic APIs, see [Intro to APIs](/docs/apis/getting-started/introduction-new-relic-apis). ## Requirements @@ -56,7 +56,7 @@ Use these methods when New Relic is not instrumenting a particular part of your - Create a new transaction. See [`newrelic.startWebTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startWebTransaction). + Create a new transaction. See [`newrelic.startWebTransaction()`](https://newrelic.github.io/node-newrelic/API.html#startWebTransaction). @@ -68,8 +68,8 @@ Use these methods when New Relic is not instrumenting a particular part of your Use either of these options: - * Return a promise from the callback handed to [`newrelic.startWebTransaction`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startWebTransaction). - * Call `end` on a [handle](http://newrelic.github.io/node-newrelic/API.html#getTransaction) (GitHub) returned from [`newrelic.getTransaction`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#getTransaction). + * Return a promise from the callback handed to [`newrelic.startWebTransaction`](https://newrelic.github.io/node-newrelic/API.html#startWebTransaction). + * Call `end` on a [handle](https://newrelic.github.io/node-newrelic/TransactionHandle.html) (GitHub) returned from [`newrelic.getTransaction`](https://newrelic.github.io/node-newrelic/API.html#getTransaction). @@ -82,45 +82,21 @@ Use these methods when New Relic is not instrumenting a particular part of your Ignore the transaction using any of these options: * See [Rules for ignoring requests](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#ignoring)`.` - * Call `ignore()` on a [handle](http://newrelic.github.io/node-newrelic/TransactionHandle.html) (GitHub) returned from [`newrelic.getTransaction`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#getTransaction). + * Call `ignore()` on a [handle](http://newrelic.github.io/node-newrelic/TransactionHandle.html) (GitHub) returned from [`newrelic.getTransaction`](https://newrelic.github.io/node-newrelic/API.html#getTransaction). +For more information about create custom web transactions, see the [startWebTransaction example on GitHub](https://github.com/newrelic/newrelic-node-examples/tree/0a036fd669b4b47b8afbc7add8696980f799f0da/custom-instrumentation/start-web-transaction). + ## Time specific methods using segments [#segments] If a transaction is already visible in New Relic, but you don't have enough data about a particular method that was called during that transaction, you can create segments to time those individual methods in greater detail. For example, you might want to time a particularly critical method with complex logic. -Use this method when you want to instrument a method within an existing transaction: - - - - - - - - - +To time a particular method, see [newrelic.startSegment](https://newrelic.github.io/node-newrelic/API.html#startSegment). - - - - - - - -
- If you want to... - - Do this... -
- Time a particular method - - See [`newrelic.startSegment()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startSegment). -
- -For more information about timing, see the [instrumentation tutorial on GitHub](http://newrelic.github.io/node-newrelic/tutorial-Instrumentation-Basics.html). +For more information about timing, see the [custom instrumentation example on GitHub](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/segments). ## Enhance the metadata of a transaction [#metadata] @@ -151,7 +127,7 @@ Use these methods when you want to change how New Relic instruments a transactio - See [`newrelic.setTransactionName`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#transaction) and [`rules.name`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#rules-name). + See [`newrelic.setTransactionName`](https://newrelic.github.io/node-newrelic/API.html#setTransactionName) and [`rules.name`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#rules-name). @@ -161,7 +137,7 @@ Use these methods when you want to change how New Relic instruments a transactio - Use [custom attributes](/docs/agents/manage-apm-agents/agent-data/collect-custom-attributes#nodejs-att). (Custom attribute collection is enabled by default in the Node.js agent.) See [`newrelic.addCustomAttribute()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#add-custom-attribute) and [`newrelic.addCustomAttributes()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#add-custom-attributes). + Use [custom attributes](/docs/agents/manage-apm-agents/agent-data/collect-custom-attributes#nodejs-att). (Custom attribute collection is enabled by default in the Node.js agent.) See [`newrelic.addCustomAttribute()`](https://newrelic.github.io/node-newrelic/API.html#addCustomAttribute) and [`newrelic.addCustomAttributes()`](https://newrelic.github.io/node-newrelic/API.html#addCustomAttributes). For more information, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/69d500e02077d2565c4762c21bf779e3e39845bf/custom-instrumentation/attributes-events-metrics) on GitHub. @@ -171,7 +147,7 @@ Use these methods when you want to change how New Relic instruments a transactio - See [`newrelic.startBackgroundTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startBackgroundTransaction). + See [`newrelic.startBackgroundTransaction()`](https://newrelic.github.io/node-newrelic/API.html#startBackgroundTransaction) and [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/background-transactions) on GitHub. @@ -181,7 +157,7 @@ Use these methods when you want to change how New Relic instruments a transactio - Use `newrelic.startWebTransaction()`. + Use [`newrelic.startWebTransaction()`](https://newrelic.github.io/node-newrelic/API.html#startWebTransaction). @@ -201,7 +177,7 @@ Use these methods when you want to change how New Relic instruments a transactio - Use the [custom metrics API](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#custom-metric-api). + Use [`recordMetric`](https://newrelic.github.io/node-newrelic/API.html#recordMetric) or [`incrementMetric`](https://newrelic.github.io/node-newrelic/API.html#incrementMetric). @@ -213,12 +189,12 @@ The agent by default sends logs directly within the context of your application' If you're using a logging mechanism that's not instrumented by New Relic, you may instead directly use this API call to record and forward your logs in context: -* [`newrelic.recordLogEvent`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#recordLogEvent) +* [`newrelic.recordLogEvent`](https://newrelic.github.io/node-newrelic/API.html#recordLogEvent) An older alternative method is to use your own log forwarder instead of letting the agent do the forwarding for you. In this case, you'll need to annotate your logs with the proper context before you forward them. Use these API calls: -* [`newrelic.getTraceMetadata`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#getTraceMetadata) -* [`newrelic.getLinkingMetadata`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#getLinkingMetadata) +* [`newrelic.getTraceMetadata`](https://newrelic.github.io/node-newrelic/API.html#getTraceMetadata) +* [`newrelic.getLinkingMetadata`](https://newrelic.github.io/node-newrelic/API.html#getLinkingMetadata) ## Instrument asynchronous work [#async] @@ -244,7 +220,7 @@ For [supported frameworks](/docs/agents/nodejs-agent/getting-started/compatibili - See [`newrelic.startSegment`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startSegment). + See [`newrelic.startSegment`](https://newrelic.github.io/node-newrelic/API.html#startSegment). @@ -254,7 +230,7 @@ For [supported frameworks](/docs/agents/nodejs-agent/getting-started/compatibili - See [`newrelic.startSegment`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startSegment). + See [`newrelic.startSegment`](https://newrelic.github.io/node-newrelic/API.html#startSegment). @@ -264,17 +240,7 @@ For [supported frameworks](/docs/agents/nodejs-agent/getting-started/compatibili - See [`newrelic.startSegment`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startSegment). You can also create your own [custom instrumentation](/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation) for libraries that are losing your transactions. - - - - - - Trace a lost transaction state - - - - A common issue is the loss of transaction state while using uninstrumented libraries. For more information, see the [transaction preservation tutorial on GitHub](http://newrelic.github.io/node-newrelic/tutorial-Context-Preservation.html). + See [`newrelic.startSegment`](https://newrelic.github.io/node-newrelic/API.html#startSegment). You can also create your own [custom instrumentation](/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation) for libraries that are losing your transactions. @@ -309,7 +275,7 @@ Once the [request naming API](/docs/agents/nodejs-agent/supported-features/nodej * [Custom instrumentation API](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#custom-instrumentation-api) * [Message queues](/docs/agents/nodejs-agent/supported-features/message-queues) - Also see the [datastore](http://newrelic.github.io/node-newrelic/DatastoreShim.html) and [message shim](http://newrelic.github.io/node-newrelic/MessageShim.html) tutorials on GitHub for . + Also see the [datastore](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/instrument-datastore) and [message shim](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/instrument-messages) example applications on GitHub. @@ -319,11 +285,7 @@ Once the [request naming API](/docs/agents/nodejs-agent/supported-features/nodej - Use [cross application tracing](/docs/apm/transactions/cross-application-traces/introduction-cross-application-traces). - - - Cross application tracing has been deprecated in favor of [Distributed tracing](/docs/enable-distributed-tracing) and will be removed in a future agent version. - + Use [distributed tracing](/docs/enable-distributed-tracing). For more information on manually inserting and accepting distributed tracing headers, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/distributed-tracing) on GitHub. @@ -341,7 +303,7 @@ Once the [request naming API](/docs/agents/nodejs-agent/supported-features/nodej ## Collect or ignore errors [#errors] -Usually the agent detects errors automatically. However, you can manually mark an error with the agent. You can also mark errors as [ignored](/docs/apm/applications-menu/error-analytics/ignoring-errors-new-relic-apm). +Usually the agent detects errors automatically. However, you can manually mark an error with the agent. You can also mark errors as [ignored](/docs/apm/applications-menu/error-analytics/ignoring-errors-new-relic-apm). For more information on using the API methods to log, group, and associate errors, use the [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/error-fingerprinting) on GitHub. @@ -363,7 +325,7 @@ Usually the agent detects errors automatically. However, you can manually mark a @@ -373,7 +335,7 @@ Usually the agent detects errors automatically. However, you can manually mark a @@ -383,7 +345,7 @@ Usually the agent detects errors automatically. However, you can manually mark a @@ -391,7 +353,8 @@ Usually the agent detects errors automatically. However, you can manually mark a ## Send custom event and metric data from your app [#custom-data] -New Relic includes a number of ways to record arbitrary custom data. For an explanation of New Relic data types, see [Data collection](/docs/data-analysis/metrics/analyze-your-metrics/data-collection-metric-timeslice-event-data). +New Relic includes a number of ways to record arbitrary custom data. For an explanation of New Relic data types, see [Data collection](/docs/data-analysis/metrics/analyze-your-metrics/data-collection-metric-timeslice-event-data). For more information on using the API methods below, use the [example application](https://github.com/newrelic/newrelic-node-examples/tree/69d500e02077d2565c4762c21bf779e3e39845bf/custom-instrumentation/attributes-events-metrics) on GitHub. +
- See [`newrelic.noticeError()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#noticeError). + See [`newrelic.noticeError()`](https://newrelic.github.io/node-newrelic/API.html#noticeError).
- See [`newrelic.setErrorGroupCallback()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#setErrorGroupCallback). + See [`newrelic.setErrorGroupCallback()`](https://newrelic.github.io/node-newrelic/API.html#setErrorGroupCallback).
- See [`newrelic.setUserId()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#setUserId). + See [`newrelic.setUserID()`](https://newrelic.github.io/node-newrelic/API.html#setUserID).
@@ -413,7 +376,7 @@ New Relic includes a number of ways to record arbitrary custom data. For an expl @@ -423,7 +386,7 @@ New Relic includes a number of ways to record arbitrary custom data. For an expl @@ -433,7 +396,7 @@ New Relic includes a number of ways to record arbitrary custom data. For an expl @@ -447,6 +410,6 @@ You can also control the browser agent via APM agent API calls. For more informa ## Extend custom instrumentation [#custom-instrumentation] -The `newrelic.instrument()` provides additional flexibility for custom instrumentation. For more information, including tutorials and examples, see the [shim documentation](http://newrelic.github.io/node-newrelic/Shim.html) on GitHub. +For more information about using the custom instrumentation APIs, see [Node.js custom instrumentation](docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-instrumentation/). -To add custom instrumentation in ES module applications, please refer to our [ES module](/docs/apm/agents/nodejs-agent/installation-configuration/es-modules) documentation or [example application](https://github.com/newrelic/newrelic-node-examples/tree/main/esm-app) in GitHub. +To add custom instrumentation in ES module applications, please refer to our [ES module](/docs/apm/agents/nodejs-agent/installation-configuration/es-modules) documentation or [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/esm-app) in GitHub. diff --git a/src/content/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api.mdx b/src/content/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api.mdx index 847f1ab458d..764252ced62 100644 --- a/src/content/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api.mdx @@ -21,7 +21,7 @@ New Relic offers several tools to help obtain the information needed to provide The number of names that New Relic tracks needs to be small enough so that the user experience is robust. It also needs to be large enough to provide the right amount of information (without overwhelming you with data) so that you can identify problem spots in your applications more easily. -For more information, see the [Node.js agent configuration](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration) documentation and the [Node.js agent API documentation on Github](https://newrelic.github.io/node-newrelic/). +For more information, see the [Node.js agent configuration](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration) documentation, the [Node.js agent API documentation on Github](https://newrelic.github.io/node-newrelic/) and [Node.js agent example applications](https://github.com/newrelic/newrelic-node-examples/tree/main). ## Request names @@ -92,7 +92,7 @@ Define your configuration rules from the most specific to the most general. The If the retailer reversed the order, the rules would catch `all` transactions in `:customer`, which would not be as useful. -## Load the request naming API [#loading] +## Load the API [#loading] Make sure that loading the New Relic module is the first thing your application does, as it needs to bootstrap itself before the rest of your application loads: @@ -100,1032 +100,30 @@ Make sure that loading the New Relic module is the first thing your application const newrelic = require('newrelic'); ``` -This returns the request naming API. You can safely require the module from multiple modules in your application, as it only initializes itself once. +This returns the New Relic Node.js API. You can safely require the module from multiple modules in your application, as it only initializes itself once. ## Request API calls [#request-api] Here is a summary of the Request API calls for New Relic's Node.js agent. + * [setTransactionName](https://newrelic.github.io/node-newrelic/API.html#setTransactionName) + * [setControllerName](https://newrelic.github.io/node-newrelic/API.html#setControllerName) - - newrelic.setTransactionName(name)} - > - ```js - newrelic.setTransactionName(name) - ``` - - Name the current request, following the [request naming requirements](#requirements). You can call this function anywhere within the context of an HTTP request handler, at any time after handling of the request has started, but before the request has finished. In general, if the request and response objects are in scope, you can set the name. - - Explicitly calling `newrelic.setTransactionName()` will override any names set by Express or Restify routes. Also, calls to `newrelic.setTransactionName()` and `newrelic.setControllerName()` will overwrite each other. The last one to run before the request ends wins. - - - newrelic.setControllerName(name, [action])} - > - ```js - newrelic.setControllerName(name, [action]) - ``` - - Name the current request using a controller-style pattern, optionally including the current controller action. If the action is omitted, New Relic will include the HTTP method (GET, POST, etc.) as the action. The rules for when you can call `newrelic.setControllerName()` are the same as they are for `newrelic.setTransactionName()`, including the [request naming requirements](#requirements). - - Explicitly calling `newrelic.setControllerName()` will override any names set by Express or Restify routes. Also, calls to `newrelic.setTransactionName()` and `newrelic.setControllerName()` will overwrite each other. The last one to run before the request ends wins. - - - -## Custom instrumentation API calls [#custom-instrumentation-api] - -Use these API calls to [expand your instrumentation with custom instrumentation](/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation). - - - newrelic.instrument(moduleName, onRequire [, onError])} - > - ```js - newrelic.instrument(moduleName, onRequire [, onError]) - ``` - - Sets an instrumentation callback for a specific module. - - The provided `onRequire` callback will be fired when the given module is loaded with `require`. The `moduleName` parameter should be the string that will be passed to `require`; for example, `'express'` or `'amqplib/callback_api'`. The optional `onError` callback is called if the `onRequire` parameters throws an error. This is useful for debugging your instrumentation. - - Use this method to: - - * Add instrumentation for modules not currently instrumented by New Relic. - * Instrument your own code. - * Replace the Node.js agent's built-in instrumentation with your own. - - For more information, see New Relic's [Node.js instrumentation tutorial on Github](https://newrelic.github.io/node-newrelic/tutorial-Instrumentation-Basics.html). - - - newrelic.instrumentDatastore(moduleName, onRequire [, onError])} - > - ```js - newrelic.instrumentDatastore(moduleName, onRequire [, onError]) - ``` - - Sets an instrumentation callback for a datastore module. - - This method is just like [`newrelic.instrument()`](#instrument), except it provides a [datastore-specialized shim](https://newrelic.github.io/node-newrelic/DatastoreShim.html). For more information, see New Relic's [Node.js datastore instrumentation tutorial on Github](https://newrelic.github.io/node-newrelic/tutorial-Datastore-Simple.html). - - - newrelic.instrumentLoadedModule(moduleName, moduleInstance)} - > - - This method is not supported or necessary in ES module applications, as agent bootstrapping in ES module applications is different than CommonJS applications. - In ES module applications, the agent is able to compensate for the issue this method solves for CommonJS applications. - - - ```js - newrelic.instrumentLoadedModule(moduleName, moduleInstance) - ``` - - The `instrumentLoadedModule` method allows you to add stock instrumentation to specific modules in situations where it's impossible to have `require('newrelic');` as the first line of your app's main module. - - ```js - // load the agent - const newrelic = require('newrelic'); - - // module loaded before newrelic - const expressModule = require('express'); - - // instrument express after the agent has been loaded - newrelic.instrumentLoadedModule( - 'express', // the module's name, as a string - expressModule // the module instance - ); - ``` - - - This method cannot instrument any arbitrary module. Its purpose is to add modules that were missed because the agent was not loaded as the first thing in your program. The `instrumentLoadedModule` method can only instrument modules the agent would normally instrument. You can see a list of these modules in the agent's [lib/instrumentations module](https://github.com/newrelic/node-newrelic/blob/0113eb5f0e707dc662a17d262a841503bab88841/lib/instrumentations.js#L6#L6). - - - - newrelic.instrumentMessages(moduleName, onRequire [, onError])} - > - ```js - newrelic.instrumentMessages(moduleName, onRequire [, onError]) - ``` - - Sets an instrumentation callback for a message service client module. - - This method is just like [`newrelic.instrument()`](#instrument), except it provides a [message-service-specialized shim](https://newrelic.github.io/node-newrelic/MessageShim.html). For more information, see New Relic's [Node.js message service instrumentation tutorial on Github](https://newrelic.github.io/node-newrelic/tutorial-Messaging-Simple.html). - - - newrelic.instrumentWebframework(moduleName, onRequire [, onError])} - > - ```js - newrelic.instrumentWebframework(moduleName, onRequire [, onError]) - ``` - - Sets an instrumentation callback for a web framework module. - - This method is just like [`newrelic.instrument()`](#instrument), except it provides a [web-framework-specialized shim](https://newrelic.github.io/node-newrelic/WebFrameworkShim.html). For more information, see New Relic's [Node.js web framework instrumentation tutorial on Github](https://newrelic.github.io/node-newrelic/tutorial-Webframework-Simple.html). - - - newrelic.startWebTransaction(url, handle)} - > - ```js - newrelic.startWebTransaction(url, handle) - ``` - - Instrument the specified web transaction. Using this API call, you can instrument transactions that New Relic [does not automatically detect](/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation#web-txn). - - * The `url` defines the transaction name and needs to be static. Do not include variable data such as user ID. - * The `handle` defines the function you want to instrument. - - New Relic will capture any metrics that would be captured by auto-instrumentation, as well as manual instrumentation via [`startSegment()`](#startSegment). - - You **must** handle custom transactions manually by calling `newrelic.getTransaction()` at the start of your transaction, and then call `transaction.end()` when you are finished. New Relic begins timing the transaction when `newrelic.startWebTransaction()` is called and ends the transaction when `transaction.end()` is called. - - You can also return a promise to indicate the end of the transaction. Please note that if this promise rejects, it does not automatically hook into New Relic's error tracking. This needs to be done manually with [`noticeError()`](#noticeError). - - Example: - - ```js - var newrelic = require("newrelic"); - newrelic.startWebTransaction("/some/url/path", function () { - var transaction = newrelic.getTransaction(); - setTimeout(function () { - // do some work - transaction.end(); - }, 100); - }); - ``` - - - newrelic.startBackgroundTransaction(name, [group], handle)} - > - ```js - newrelic.startBackgroundTransaction(name, [group], handle) - ``` - - Instrument the specified background transaction. Using this API call, you can expand New Relic's instrumentation to [capture data from background transactions](/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation#background-txn). - - * The `name` defines the transaction name and needs to be static. Do not include variable data such as user ID. - * The `group` is optional, and it allows you to group similar jobs together via the [**transaction type** in the user interface](/docs/apm/applications-menu/monitoring/transactions-dashboard#txn-type-dropdown). Like `name`, the `group` needs to be static. - * The `handle` defines a function that includes the entire background job you want to instrument. - - New Relic will capture any metrics that would be captured by auto-instrumentation, as well as manual instrumentation via [`startSegment()`](#startSegment). - - You **must** handle custom transactions manually by calling `newrelic.getTransaction()` at the start of your transaction, and then call `transaction.end()` when you are finished. New Relic begins timing the transaction when `newrelic.startBackgroundTransaction()` is called and ends the transaction when `transaction.end()` is called. - - You can also return a promise to indicate the end of the transaction. Please note that if this promise rejects, it does not automatically hook into New Relic’s error tracking. This needs to be done manually with [`noticeError()`](#noticeError). - - Example: - - ```js - var newrelic = require("newrelic"); - newrelic.startBackgroundTransaction("Red October", "Subs", function () { - var transaction = newrelic.getTransaction(); - setTimeout(function () { - // do some work - transaction.end(); - }, 100); - }); - ``` - - - newrelic.getTransaction()} - > - ```js - newrelic.getTransaction() - ``` - - Returns a handle on the currently executing transaction. This handle can then be used to interact with a given transaction safely from any context. It is best used with `newrelic.startWebTransaction()` and `newrelic.startBackgroundTransaction()`. - - [Please refer to the transaction handle section for more details.](#transaction-handle-methods) - - - newrelic.endTransaction()} - > - ```js - newrelic.endTransaction() - ``` - - End the current [web](#createWebTransaction) or [background](#createBackgroundTransaction) custom transaction. This method requires being in the correct transaction context when called. This API call takes no arguments. - - - newrelic.startSegment(name, record, handler, callback)} - > - ```js - newrelic.startSegment(name, record, handler, callback) - ``` - - Instrument a particular method to [improve visibility into a transaction](/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation#expanding-instrumentation), or optionally turn it into a metric. - - * The `name` defines a name for the segment. This name will be visible in transaction traces and as a new metric in the New Relic UI. - * The `record` flag defines whether the segment should be recorded as a metric. - * The `handler` is the function you want to track as a segment. - * The optional `callback` is a function passed to the handler to fire after its work is done. - - The agent begins timing the segment when `startSegment` is called. The segment is ended when either the `handler` finishes executing, or `callback` is fired, if it is provided. - - Example: - - ```js - newrelic.startSegment('mySegment', false, function handler() { - // The returned promise here will signify the end of the segment. - return myAsyncTask().then(myNextTask) - }) - ``` - - - -## Custom metrics API calls [#custom-metric-api] - -Use these API calls to [record additional arbitrary metrics](/docs/agents/nodejs-agent/supported-features/nodejs-custom-metrics): - - - newrelic.recordMetric(name, value)} - > - ```js - newrelic.recordMetric(name, value) - ``` - - Use `recordMetric` to 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, any other keys will be ignored. 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. - - - newrelic.incrementMetric(name, [amount])} - > - ```js - newrelic.incrementMetric(name, [amount]) - ``` - - Use `incrementMetric` to 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. - - - -## Custom events API calls [#custom-events-api] - -Use these API calls to record additional events: - - - newrelic.recordCustomEvent(eventType, attributes)} - > - ```js - newrelic.recordCustomEvent(eventType, attributes) - ``` - - Use `recordCustomEvent` to record an event-based metric, usually associated with a particular duration. - - * The `eventType` must be an alphanumeric string less than 255 characters. - * The `attributes` must be an object of key and value pairs. The keys must be shorter than 255 characters, and the values must be string, number, or boolean. - - - - The following example demonstrates recording a custom event with multiple attributes. - - ```js - const attributes = { - attribute1: 'value1', - attribute2: 2 - }; - - newrelic.recordCustomEvent('MessagingEvent', attributes); - ``` - - - - - - - newrelic.recordLogEvent(logEvent)} - > - ```js - newrelic.recordLogEvent({message, level}) - ``` - - Use `recordLogEvent` to record a log event, in case that automatic logging instrumentation is insufficient for your logging framework. [Consult the auto-generated documentation](https://newrelic.github.io/node-newrelic/API.html#recordLogEvent) for the details of the parameter types accepted. - - - - The following example demonstrates recording a log event associated to an error. - - ```js - const error = new SystemError('invalid state'); - const timestamp = Date.now(); - - newrelic.recordLogEvent({message: 'an error happened', level: 'error', timestamp, error}); - ``` - - - - - -## Transaction handle methods [#transaction-handle-methods] - -This section details the methods provided by the `TransactionHandle` class instance that can be obtained through `newrelic.getTransaction()`. - -Use these methods to interact directly with the current transaction: - - - transactionHandle.end([callback])} - > - ```js - transactionHandle.end([callback]) - ``` - - Use `transactionHandle.end` to end the transaction referenced by the handle instance. - - The `callback` is invoked when the transaction has fully ended. The finished transaction passed to the callback as the first argument. - - - transactionHandle.ignore()} - > - ```js - transactionHandle.ignore() - ``` - - Use `transactionHandle.ignore` to ignore the transaction referenced by the handle instance. - - - transactionHandle.insertDistributedTraceHeaders(headers)} - > - ```js - transactionHandle.insertDistributedTraceHeaders(headers) - ``` - - - This API requires [distributed tracing to be enabled](/docs/enable-distributed-tracing). - - - For context on how to use this call and its partner call `acceptDistributedTraceHeaders`, first read [Enable distributed tracing with agent APIs](/docs/enable-distributed-tracing#agent-apis). - - `transactionHandle.insertDistributedTraceHeaders` is used to implement distributed tracing. It modifies the `headers` map that is passed in by adding W3C Trace Context headers and New Relic Distributed Trace headers. The New Relic headers can be disabled with `distributed_tracing.exclude_newrelic_header: true` in the config. This method replaces the deprecated [`createDistributedTracePayload`](#transaction-handle-createDistributedTracePayload) method, which only creates New Relic Distributed Trace payloads. - - - - In the following example, by calling insertDistributedTraceHeaders with an empty object, the appropriate Distributed Trace headers and W3C Trace Context headers will be generated for the transaction. - - ```js - // Call newrelic.getTransaction to retrieve a handle on the current transaction. - const transactionHandle = newrelic.getTransaction(); - - // This could be a header object from an incoming request as well - const headersObject = {}; - newrelic.startBackgroundTransaction('background task', function executeTransaction() { - const transaction = newrelic.getTransaction(); - // generate the headers - transaction.insertDistributedTraceHeaders(headersObject); - }); - ``` - - - - - transactionHandle.acceptDistributedTraceHeaders(transportType, headers)} - > - ```js - transactionHandle.acceptDistributedTraceHeaders(transportType, headers) - ``` - - - This API requires [distributed tracing to be enabled](/docs/enable-distributed-tracing). - - - For context on how to use this call and its partner call `insertDistributedTraceHeaders`, first read [Enable distributed tracing with agent APIs](/docs/enable-distributed-tracing#agent-apis). - - `transactionHandle.acceptDistributedTraceHeaders` is used to instrument the called service for inclusion in a distributed trace. It links the spans in a trace by accepting a payload generated by [`insertDistributedTraceHeaders`](#transaction-handle-insertDistributedTraceHeaders) or generated by some other W3C Trace Context compliant tracer. This method accepts the headers of an incoming request, looks for W3C Trace Context headers, and if not found, falls back to New Relic distributed trace headers. This method replaces the deprecated (and now removed as of version 7.0.0) [`acceptDistributedTracePayload`](#transaction-handle-acceptDistributedTracePayload) method, which only handles New Relic distributed trace payloads. - - `transportType` should be one of the following strings: - - * `AMQP` - * `HTTP` - * `HTTPS` - * `IronMQ` - * `JMS` - * `Kafka` - * `Other` - * `Queue` - * `Unknown` - - `headers` should be an object containing all the headers in the incoming request. The keys must be lowercase. - - - - The following example demonstrates adding distributed trace headers retrieved from a Kafka message. In this example, we assume that the incoming Kafka message has Distributed Trace headers inserted. - - ```js - // incoming Kafka message headers - const headersObject = message.headers; - - // Call newrelic.getTransaction to retrieve a handle on the current transaction. - const transactionHandle = newrelic.getTransaction(); - - newrelic.startBackgroundTransaction('background task', function executeTransaction() { - const transaction = newrelic.getTransaction(); - - // accept the headers - transaction.acceptDistributedTraceHeaders('Kafka', headersObject); - }); - ``` - - - - - transactionHandle.createDistributedTracePayload()} - > - ```js - transactionHandle.createDistributedTracePayload() - ``` - - - This method is deprecated and was removed in version 7.0.0! Please use `insertDistributedTraceHeaders.` - - - - This API requires [distributed tracing to be enabled](/docs/enable-distributed-tracing). - - - For instructions on how to use this call, along with its partner call [`acceptDistributedTracePayload`](#transaction-handle-acceptDistributedTracePayload), see [Enable distributed tracing with agent APIs](/docs/enable-distributed-tracing#agent-apis). - - This call is used to implement distributed tracing. It generates a payload that is read by the receiving application with [`acceptDistributedTracePayload`](#transaction-handle-acceptDistributedTracePayload). - - - Note: In order to maintain proper ordering of spans in a trace, you must generate the payload in the context of the span that sends it. - - - The `DistributedTracePayload` object has two available methods used for generating the payload in different formats: - - * `DistributedTracePayload#text`: returns a JSON representation of the payload. - - - - ```js - // Call newrelic.getTransaction to retrieve a handle on the current transaction. - var transactionHandle = newrelic.getTransaction(); - var payload = transactionHandle.createDistributedTracePayload(); - var jsonPayload = payload.text(); - newrelic.startBackgroundTransaction('background task', function executeTransaction() { - var backgroundHandle = newrelic.getTransaction(); - // Link the nested transaction by accepting the payload with the background transaction's handle - backgroundHandle.acceptDistributedTracePayload(jsonPayload); - }); - ``` - - - * `DistributedTracePayload#httpSafe`: returns a base64 encoded JSON representation of the payload. - - - - ```js - // Call newrelic.getTransaction to retrieve a handle on the current transaction. - var transactionHandle = newrelic.getTransaction(); - var payload = transactionHandle.createDistributedTracePayload(); - // Place the base64 encoded value on an outbound request header. - req.headers[myTracingHeader] = payload.httpSafe(); - ``` - - - - - transactionHandle.acceptDistributedTracePayload(payload)} - > - ```js - transactionHandle.acceptDistributedTracePayload(payload) - ``` - - - This method is deprecated and was removed in version 7.0.0! Please use `acceptDistributedTraceHeaders.` - - - - This API requires [distributed tracing to be enabled](/docs/enable-distributed-tracing). - - - For context on how to use this call and its partner call `createDistributedTracePayload`, first read [Enable distributed tracing with agent APIs](/docs/enable-distributed-tracing#agent-apis). - - `transactionHandle.acceptDistributedTracePayload` is used to instrument the called service for inclusion in a distributed trace. It links the spans in a trace by accepting the payload generated by [`createDistributedTracePayload`](#transaction-handle-createDistributedTracePayload). - - - transactionHandle.isSampled()} - > - ```js - transactionHandle.isSampled() - ``` - - Returns whether this trace is being sampled. - - - -## Other API calls [#other-api] - -New Relic's Node.js agent includes additional API calls. - - - newrelic.addCustomAttribute(name, value)} - > - ```js - newrelic.addCustomAttribute(name, value) - ``` - - Set a custom attribute value to be displayed along with the transaction trace in the New Relic UI. This must be called within the context of a transaction so it has a place to set the custom attributes. Custom attributes will appear in APM's transaction trace detail view and in errors for the transaction. - - - - ```js - newrelic.addCustomAttribute('attribute1', 'value1') - ``` - - - - - If you want to use your custom attributes, avoid using any of the [reserved terms used by NRQL](/docs/insights/event-data-sources/custom-events/data-requirements-limits-custom-event-data/#reserved-words) when naming them. - - - - newrelic.addCustomAttributes(attributes)} - > - ```js - newrelic.addCustomAttributes(attributes) - ``` - - Set multiple custom attribute values to be displayed along with the transaction trace in the New Relic UI. The attributes should be passed as a single object. This must be called within the context of a transaction so it has a place to set the custom attributes. Custom attributes will appear in the transaction trace detail view and in errors for the transaction. - - - - ```js - const attributes = { - attribute1: 'value1', - attribute2: 2 - }; - - newrelic.addCustomAttributes(attributes); - ``` - - - - - If you want to use your custom attributes, avoid using any of the [reserved terms used by NRQL](/docs/insights/event-data-sources/custom-events/data-requirements-limits-custom-event-data/#reserved-words) when naming them. - - - - newrelic.addCustomSpanAttribute(name, value)}> - ```js - newrelic.addCustomSpanAttribute(name, value) - ``` - - Set a custom span attribute value to be displayed along with a transaction trace span in the New Relic UI. This must be called within the context of an active segment/span so it has a place to set the custom span attributes. Custom span attributes will appear in the Attributes section of the span detail view. - - - - ```js - newrelic.addCustomSpanAttribute('attribute1', 'value') - ``` - - - - - This API requires [distributed tracing](/docs/enable-distributed-tracing) and [span events](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration#span-events) to be enabled. - - - - If you want to use your custom span attributes, avoid using any of the [reserved terms used by NRQL](/docs/insights/event-data-sources/custom-events/data-requirements-limits-custom-event-data/#reserved-words) when naming them. - - - - newrelic.addCustomSpanAttributes(attributes)}> - ```js - newrelic.addCustomSpanAttributes(attributes) - ``` - - Set multiple custom span attribute values to be displayed along with the transaction trace spans in the New Relic UI. The attributes should be passed as a single object. This must be called within the context of an active segment/span so it has a place to set the custom span attributes. Custom span attributes will appear in the Attributes section of the span detail view. - - - - ```js - const attributes = { - attribute1: 'value1', - attribute2: 'value2' - }; - - newrelic.addCustomSpanAttributes(attributes); - ``` - - - - - This API requires [distributed tracing](/docs/enable-distributed-tracing) and [span events](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration#span-events) to be enabled. - - - - If you want to use your custom span attributes, avoid using any of the [reserved terms used by NRQL](/docs/insights/event-data-sources/custom-events/data-requirements-limits-custom-event-data/#reserved-words) when naming them. - - - - newrelic.getBrowserTimingHeader()} - > - ```js - newrelic.getBrowserTimingHeader() - ``` - - Returns the HTML snippet to be inserted into the header of HTML pages to enable [](/docs/agents/nodejs-agent/supported-features/page-load-timing-nodejs). The HTML will instruct the browser to fetch a small JavaScript file and start the page timer. - - - newrelic.noticeError(error, [customAttributes], [expected])} - > - ```js - newrelic.noticeError(error, [customAttributes], [expected]) - ``` - - Use this call if your app is doing its own error handling with domains or try/catch clauses, but you want all of the information about how many errors are coming out of the app to be centrally managed. Unlike other Node.js calls, this can be used outside of route handlers, but it will have additional context if called from within transaction scope. - - `error` 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. - - `customAttributes` is an optional object of any custom attributes to be displayed in the New Relic UI. - - `expected` is an optional boolean to classify the error as an error you expect. If an error collected with `noticeError` is `expected`, it will be collected and reported, but will not affect `Apdex` or error rate metrics. By default, `expected` is `false`. - - - The `expected` parameter requires [Node.js agent version 9.12.1](/docs/release-notes/agent-release-notes/nodejs-release-notes/node-agent-9-12-1) or higher. - - - - **Example:** - - - ```js - try { - performSomeTask(); - } catch(err) { - newrelic.noticeError( - err, - { extraInformation: "error already handled in the application" }, - true - ); - } - ``` - - - Errors recorded using this method do not obey the [`ignore_status_codes`](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration#error_ignore) configuration value. - - - - newrelic.setErrorGroupCallback(callback)} - > - ```js - newrelic.setErrorGroupCallback(callback) - ``` - - This method lets you define a custom callback to generate error group names, which will be used by 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. The object contains information related to the error that occurred, and has the following format: - - - Use of `setErrorGroupCallback` requires [Node.js agent version 9.14.0](/docs/release-notes/agent-release-notes/nodejs-release-notes/node-agent-9-14-0/) or higher. - - - ```js - { - "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 versions of this callback function. Example: - - ```js - function myCallback(metadata) { - if (metadata['http.statusCode'] === '400') { - return 'Bad User Input' - } - } - - newrelic.setErrorGroupCallback(myCallback) - ``` - - To learn more about this function, please refer to our [example app](https://github.com/newrelic/newrelic-node-examples/tree/main/error-fingerprinting). - - - newrelic.setIgnoreTransaction(ignored)} - > - - This method is deprecated and was removed in version 7.0.0. Please use [transactionHandle.ignore()](#transaction-handle-ignore) - - - ```js - newrelic.setIgnoreTransaction(ignored) - ``` - - Tell the module whether or not to ignore a given request. This allows you to explicitly filter long-polling, irrelevant routes or requests you know will be time-consuming. This also allows you to gather metrics for requests that otherwise would be ignored. - - * To ignore the transaction, set the parameter to `true`: this will ignore the transaction. - * To prevent a transaction from being ignored with this function, pass the parameter `false`. - * Passing `null` or `undefined` will not change whether the transaction is ignored. - - - newrelic.setUserID(string)} - > - ```js - newrelic.setUserID(string) - ``` - - This method gives you a way to associate a unique identifier with a transaction event, transaction trace and errors within transaction. A new property, `enduser.id`, will be added to the error and reported to errors inbox. - - - The `setUserID` API requires [Node.js agent version 9.13.0](/docs/release-notes/agent-release-notes/nodejs-release-notes/node-agent-9-13-0/) or higher. - - - - newrelic.shutdown([options], callback)} - > - ```js - newrelic.shutdown(options, callback) - ``` - - Use this method to gracefully shut down the agent, both parameters are optional. Here's an overview table showing the parameters: - -
- Create a [custom event](/docs/insights/insights-data-sources/custom-data/insert-custom-events-new-relic-apm-agents#node-att). See [`newrelic.recordCustomEvent()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#record_custom_event). + Create a [custom event](/docs/insights/insights-data-sources/custom-data/insert-custom-events-new-relic-apm-agents#node-att). See [`newrelic.recordCustomEvent()`](https://newrelic.github.io/node-newrelic/API.html#recordCustomEvent).
- Add [custom attributes](/docs/agents/manage-apm-agents/agent-data/collect-custom-attributes#nodejs=att) if needed. (Custom attribute collection is enabled by default in the Node.js agent.) See [`newrelic.addCustomAttribute()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#add-custom-attribute) and [`newrelic.addCustomAttributes()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#add-custom-attributes). + Add [custom attributes](/docs/agents/manage-apm-agents/agent-data/collect-custom-attributes#nodejs=att) if needed. (Custom attribute collection is enabled by default in the Node.js agent.) See [`newrelic.addCustomAttribute()`](https://newrelic.github.io/node-newrelic/API.html#addCustomAttribute) and [`newrelic.addCustomAttributes()`](https://newrelic.github.io/node-newrelic/API.html#addCustomAttributes).
- Create a [custom metric](/docs/agents/manage-apm-agents/agent-data/custom-metrics). See [`newrelic.recordMetric()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#record_metric) and [`newrelic.incrementMetric()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#increment_metric). To view the data, use [**metrics and events**](/docs/query-your-data/explore-query-data/data-explorer/introduction-data-explorer). + Create a [custom metric](/docs/agents/manage-apm-agents/agent-data/custom-metrics). See [`newrelic.recordMetric()`](https://newrelic.github.io/node-newrelic/API.html#recordMetric) and [`newrelic.incrementMetric()`](https://newrelic.github.io/node-newrelic/API.html#incrementMetric). To view the data, use [**metrics and events**](/docs/query-your-data/explore-query-data/data-explorer/introduction-data-explorer).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Parameter - - Type - - Attributes - - Description -
- `options ` - - `object` - - Optional - - Object with shut down options -
- `callback` - - `function` - - Optional - - Callback function that runs when agent stops -
- - Here is a detail table showing the object shutdown options: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Option name - - Type - - Attributes - - Default - - Description -
- `collectPendingData` - - `boolean` - - Optional - - `false` - - Tell the agent whether to send any pending data to the New Relic collector before shutting down. -
- `timeout` - - `number` - - Optional - - `0` - - The default time before forcing a shutdown. When `collectPendingData` is true, the agent will wait for a connection before shutting down. This timeout is useful for short lived processes, like AWS Lambda, in order to keep the process from staying open too long, while trying to connect. -
- `waitForIdle` - - `boolean` - - Optional - - `false` - - If `true`, the agent will not shut down until there are no active transactions. -
- - - **Example:** - - - ```js - newrelic.shutdown({collectPendingData: true, timeout: 10000}, (error) => { - process.exit(); - }); - ``` - +## Custom instrumentation API calls [#custom-instrumentation-api] - newrelic.getLinkingMetadata()} - > - ```js - newrelic.getLinkingMetadata() - ``` +Use these API calls to [expand your instrumentation with custom instrumentation](/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation). - Returns key/value pairs which can be used to link traces or entities. +## Custom metrics API calls [#custom-metric-api] - It will only contain items with meaningful values. For instance, if distributed tracing is disabled, `trace.id` will not be included. - +Use these API calls to [record additional arbitrary metrics](/docs/agents/nodejs-agent/supported-features/nodejs-custom-metrics). - newrelic.getTraceMetadata()} - > - ```js - newrelic.getTraceMetadata() - ``` +## Custom events API calls [#custom-events-api] - Returns and object containing the current trace ID and span ID. +Use these API calls to record additional events: + * [recordCustomEvent](https://newrelic.github.io/node-newrelic/API.html#recordCustomEvent) + * [recordLogEvent](https://newrelic.github.io/node-newrelic/API.html#recordLogEvent) - - This API requires [distributed tracing to be enabled](/docs/enable-distributed-tracing) or an empty object will be returned. - - - +## Transaction handle methods +Use these API calls to [interact with the current transaction](https://newrelic.github.io/node-newrelic/TransactionHandle.html) ## Rules for naming and ignoring requests [#ignoring] @@ -1357,18 +355,6 @@ Here are full examples of how rules are included in the configuration file: Here are the API calls for naming and ignoring rules with New Relic's Node.js agent. - - newrelic.addNamingRule(pattern, name)} - > - Programmatic version of **rules.name**. Once naming rules are added, they cannot be removed until the Node.js process is restarted. They can also be added via the Node.js agent's configuration. Both parameters are required. - + * [addNamingRule](https://newrelic.github.io/node-newrelic/API.html#addNamingRule) + * [addIgnoringRule](https://newrelic.github.io/node-newrelic/API.html#addIgnoringRule) - newrelic.addIgnoringRule(pattern)} - > - Programmatic version of **rules.ignore**. Once ignoring rules are added, they cannot be removed until the Node.js process is restarted. They can also be added via the Node.js agent's configuration. This parameter is required. - - diff --git a/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-instrumentation.mdx b/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-instrumentation.mdx index 7bfa3de8b27..f8f20e93bb6 100644 --- a/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-instrumentation.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-instrumentation.mdx @@ -14,7 +14,7 @@ redirects: freshnessValidatedDate: never --- -New Relic for Node.js automatically instruments most standard web requests, but sometimes you want expanded instrumentation. With the agent's custom instrumentation API, you can create instrumentation for otherwise unsupported [web frameworks](#web-framework), [datastores](#datastore), and [message service clients](#message-client). +New Relic for Node.js automatically instruments most standard web requests, but sometimes you want expanded instrumentation. With the agent's [custom instrumentation API](https://newrelic.github.io/node-newrelic/API.html), you can create instrumentation for otherwise unsupported [web frameworks](#web-framework), [datastores](#datastore), and [message service clients](#message-client). The Node.js agent's custom instrumentation API also allows you to: @@ -28,118 +28,21 @@ The custom instrumentation methods in this document are available as of [Node.js ## Instrument unsupported web frameworks [#web-framework] -Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional web frameworks. For more information, including a tutorial, see the documentation for the [Node.js web framework instrumentation](http://newrelic.github.io/node-newrelic/tutorial-Webframework-Simple.html) on GitHub. +Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional web frameworks. For more information, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/instrument-webframework) on GitHub. ## Instrument unsupported message service clients [#message-client] -Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional message service libraries. For more information, including a tutorial, see the documentation for the [Node.js message service client instrumentation](http://newrelic.github.io/node-newrelic/tutorial-Messaging-Simple.html) on GitHub. +Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional message service libraries. For more information, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/instrument-messages) on GitHub. ## Instrument unsupported datastores [#datastore] -Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional datastore libraries. For more information, including a tutorial, see the documentation for the [Node.js datastore instrumentation](http://newrelic.github.io/node-newrelic/tutorial-Datastore-Simple.html) on GitHub. +Beginning with Node.js agent version 2.0.0, New Relic provides an API to expand instrumentation for additional datastore libraries. For more information, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/instrument-datastore) on GitHub. ## Instrument web transactions [#web-txn] -In order to create custom [web transactions](/docs/apm/transactions/intro-transactions/transactions-new-relic-apm), call `startWebTransaction` to start the transaction. To end the transaction, use any of these options: +In order to create custom [web transactions](/docs/apm/transactions/intro-transactions/transactions-new-relic-apm), call `startWebTransaction` to start the transaction. For more information, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/0a036fd669b4b47b8afbc7add8696980f799f0da/custom-instrumentation/start-web-transaction) on GitHub. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - **Ending the transaction** - - - - **Comments** - -
- Promise - - If the handler passed to `startWebTransaction` returns a promise, the agent will end the transaction when the returned promise resolves or rejects. -
- Manual - - If you call `getTransaction` in the context of the new transaction, this notifies the agent that the transaction will be handled manually. - - If `getTransaction` is called in the handler, then you **must** end the transaction by calling `transaction.end()`. -
- Synchronous - - If neither of these options are fulfilled, the transaction will be ended when the handler returns synchronously. -
- - - - This example instruments a `/websocket/ping` transaction, a `/websocket/update` transaction, and a `/websocket/new-message` transaction within `socket.io`. The `/ping` example is synchronous, while the `/new-message` and `/update` examples are asynchronous. - - ```js - const nr = require('newrelic'); - const app = require('http').createServer(); - const io = require('socket.io')(app); - - io.on('connection', function(socket) { - socket.on('ping', function(data) { - nr.startWebTransaction('/websocket/ping', function transactionHandler() { - // Ended automatically after synchronously returning - socket.emit('pong'); - }); - }); - socket.on('update', function(data) { - nr.startWebTransaction('/websocket/update', function transactionHandler() { - // Using API getTransaction - const transaction = nr.getTransaction(); - updateChatWindow(data, function transactionHandler() { - socket.emit('update-done'); - transaction.end(); - }); - }); - }); - socket.on('new-message', function(data) { - nr.startWebTransaction('/websocket/new-message', function transactionHandler() { - // Returning a promise - return new Promise(function(resolve, reject) { - addMessageToChat(data, function() { - socket.emit('message-received'); - resolve(); - }); - }); - }); - }); - }); - ``` - - This method only gives basic timing data for the transaction created. To create more intricate timing data and transaction naming for a particular framework, see the [Node.js API docs](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#instrumentWebframework) and the [related WebFramework tutorial](http://newrelic.github.io/node-newrelic/tutorial-Webframework-Simple.html) on GitHub. - - +The linked example application only gives basic timing data for the transaction created. To create more intricate timing data and transaction naming for a particular framework, see the [Node.js API docs](https://newrelic.github.io/node-newrelic/API.html#instrumentWebframework) and the [related WebFramework example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/instrument-webframework) on GitHub. ## Instrument background transactions [#background-txn] @@ -148,247 +51,11 @@ You can use custom transactions to instrument [non-web transactions](/docs/apm/t * Periodic jobs within your app * Work that continues after a request completes -To instrument background tasks, call [`startBackgroundTransaction`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startBackgroundTransaction) in your handler to start a background transaction. To end the transaction, use any of these options: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - **Ending the transaction** - - - - **Comments** - -
- Promise - - If the handler passed to `startBackgroundTransaction` returns a promise, the agent will end the transaction when the returned promise resolves or rejects. -
- Manual - - If you call `getTransaction` in the context of the new transaction, this notifies the agent that the transaction will be handled manually. - - If `getTransaction` is called in the handler, then you **must** end the transaction by calling `transaction.end()`. -
- Synchronous - - If neither of these options are fulfilled, the transaction will be ended when the handler returns synchronously. -
- - - - This example instruments `update:cache` within `setInterval`: - - ```js - const nr = require('newrelic'); - const redis = require('redis').createClient(); - - // Using API getTransaction to manage ending the transaction - setInterval(function() { - nr.startBackgroundTransaction('update:cache', function transactionHandler() { - const newValue = someDataGenerator(); - const transaction = nr.getTransaction(); - - redis.set('some:cache:key', newValue, function() { - transaction.end(); - }); - }); - }, 30000); // Every 30s - - //Using a promise to manage ending the transaction - setInterval(function() { - nr.startBackgroundTransaction('flush:cache', function transactionHandler() { - return new Promise(function(resolve, reject) { - flushCache(redis, function afterFlush(err) { - if (err) { - return reject(err); - } - resolve(); - }); - }); - }); - }, 60 * 60 * 1000); - ``` - - +To instrument background tasks, call [`startBackgroundTransaction`](https://newrelic.github.io/node-newrelic/API.html#startBackgroundTransaction) in your handler to start a background transaction. For more information, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/background-transactions) on GitHub. ## Expand instrumentation within transactions [#expanding-instrumentation] -You can create instrumentation using the [instrumentation registration methods on the API](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#custom-instrumentation-api). Writing instrumentation using the instrumentation API allows you to specify metrics and naming in greater detail by "monkey patching" methods (replacing functions) on relevant objects. Other options can offer visibility into web transactions that are already instrumented, or gain insight into databases and other in-transaction work that is not automatically instrumented. - -To do this, wrap your callbacks in custom tracers. Custom tracers create and collect specific metrics for an additional segment within an existing transaction, such as a particular function or a database call. - -* To instrument individual callbacks, call `startSegment()` inside the callback, and move the main callback logic to the `handler` function. -* To instrument a function that is called inside an asynchronous function, wrap both the target function and its parent asynchronous function with [`startSegment()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#startSegment). - - - These examples must be placed in code that is running under a transaction. The origin of the transaction, custom or automatically created, does not matter. - - - - - This example tracks a single callback: - - ```js - // Wrap the method in a segment. - nr.startSegment('db:createObject', true, function(cb) { - // This is recorded as the `db:createObject` segment. - db.createObject(cb); - }, function(err, result) { - // This is recorded as the callback to the `db:createObject` segment. - if (util.handleError(err, res)) { - return; - } - res.write(JSON.stringify(result.rows[0].id)); - res.write('\n'); - res.end(); - }); - ``` - - - - This example tracks both `pg.connect` and `client.query`. This is because `client.query` is called by an asynchronous parent function (`pg.connect`). Otherwise, you would not get any data from `client.query`. This allows `startSegment()` to propagate the active transaction across those asynchronous boundaries. - - ```js - nr.startSegment('pg:connect', true, function(cb) { - pg.connect(config.db_string, cb); - }, function(err, client, done) { - if (util.handleError(err, '500', res)) { - return done(); - } - - nr.startSegment('pg:query', true, function(cb) { - client.query('SELECT count(*) FROM test_count', cb); - }, function(err, result) { - if (util.handleError(err, '500', res)) { - return done(); - } - - res.write(result.rows[0].count); - res.write('\n'); - }); - }); - ``` - - - - This example is the same as the callback one, but for interacting with a promise-based API. For promises, simply return the promise and call `then` after `startSegment` to continue your execution. - - ```js - nr.startSegment('pg:connect', true, function() { - // This `pg:connect` segment will time until the returned promise - // either resolves or rejects. - return pg.connect(config.db_string); - }).then(function(client) { - // The transaction context is propagated into following promises. - return nr.startSegment('pg:query', true, function() { - return client.query('SELECT count(*) FROM test_count'); - }).then(function(result) { - res.write(result.rows[0].count); - res.write('\n'); - res.end(); - }, function(err) { - // Error from querying. - util.handleError(err, '500', res); - }).finally(function() { - return client.release(); - }); - }, function(err) { - // Error from connecting. - util.handleError(err, '500', res); - }); - ``` - - - Example: Instrument async functions} - > - This example shows how to instrument code using `async`/`await` to control asynchronous work. This requires using Node.js 8 or higher, as well as the New Relic for Node.js agent v2.3.0 or higher. - - ```js - try { - const client = await nr.startSegment('pg:connect', true, async () => { - // Async functions simply return promises, so this example is - // very similar to the promise one. - return await pg.connect(config.db_string); - }); - - // The transaction context is propagated into the code following `await`. - try { - const result = await nr.startSegment('pg:query', true, async () => { - return await client.query('SELECT count(*) FROM test_count'); - }); - - res.write(result.rows[0].count); - res.write('\n'); - res.end(); - } catch (err) { - // Error from querying. - util.handleError(err, '500', res); - } finally { - await client.release(); - } - } catch (err) { - // Error from connecting. - util.handleError(err, '500', res); - } - ``` - - - - This example shows how `startSegment` can be used to record a synchronous function that is responsible for assigning its return value to a variable. +You can create instrumentation using the [instrumentation registration methods on the API](https://newrelic.github.io/node-newrelic/API.html#instrument). Writing instrumentation using the instrumentation API allows you to specify metrics and naming in greater detail by "monkey patching" methods (replacing functions) on relevant objects. Other options can offer visibility into web transactions that are already instrumented, or gain insight into databases and other in-transaction work that is not automatically instrumented. - ```js - const result = nr.startSegment('calculateTotal', true, function() { - return calculateTotal(outerVar1, outerVar2); - }); - ``` +To do this, wrap your callbacks in custom tracers. Custom tracers create and collect specific metrics for an additional segment within an existing transaction, such as a particular function or a database call. For more information, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/segments) on GitHub. - - The `startSegment` function is available of the Node.js agent 3.3.0 release. - - - diff --git a/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-metrics.mdx b/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-metrics.mdx index 9d449c16b25..6b535aef168 100644 --- a/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-metrics.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-custom-metrics.mdx @@ -35,21 +35,7 @@ For custom metric names, use `/` or `/`. For exam The public API for recording metric data consists of two methods on `newrelic`: -* [`recordMetric`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#record_metric): Use to create a new custom metric. -* [`incrementMetric`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#increment_metric): Use to update the value of a custom metric. +* [`recordMetric`](https://newrelic.github.io/node-newrelic/API.html#recordMetric): Use to create a new custom metric. +* [`incrementMetric`](https://newrelic.github.io/node-newrelic/API.html#incrementMetric): Use to update the value of a custom metric. -## Example custom metric [#example] - -Here is an example that shows how you can use metrics to track currency flowing through a site: - -```js -app.post('/cart/checkout', function(req, res) { - var total = computeCartTotal(req.user); - newrelic.recordMetric('Cart/ChargeAmount', total); - // ... -}); -``` - -## View custom metrics [#viewing-custom] - -To view custom metrics, see [visualize your custom metric after creating it](/docs/query-your-data/explore-query-data/data-explorer/introduction-data-explorer#visualize-metric) and [metrics and events](/docs/query-your-data/explore-query-data/data-explorer/introduction-data-explorer) to search metrics, create customizable charts, and add those charts to New Relic dashboards. +For more information, see the [example application](https://github.com/newrelic/newrelic-node-examples/tree/69d500e02077d2565c4762c21bf779e3e39845bf/custom-instrumentation/attributes-events-metrics) on GitHub. diff --git a/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx b/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx deleted file mode 100644 index c9e6186082e..00000000000 --- a/src/content/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Node.js v1 custom instrumentation (legacy) -tags: - - Agents - - Nodejs agent - - Extend your instrumentation -metaDescription: 'Expand your Node.js instrumentation in New Relic to cover uninstrumented frameworks, databases, segments. Use custom tracers to better track async work.' -redirects: - - /docs/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy - - /docs/agents/nodejs-agent/supported-features/nodejs-v1x-custom-instrumentation-legacy - - /docs/agents/nodejs-agent/supported-features/nodejs-v1-custom-instrumentation-legacy -freshnessValidatedDate: never ---- - -New Relic for Node.js automatically instruments most standard web requests, but sometimes you want expanded instrumentation. With custom instrumentation, you can instrument [web sockets](#web-txn), [background jobs](#background-txn), and [unsupported databases](#expanding-instrumentation). Custom instrumentation can also [target specific sections of your code for deeper insight](#expanding-instrumentation). - -Custom instrumentation is available in versions 1.10.0 or higher of the Node.js agent. To take advantage of the latest Node.js agent features, [upgrade your agent](/docs/agents/nodejs-agent/installation-configuration/upgrade-nodejs-agent). - -## Instrumenting web transactions [#web-txn] - -To instrument web transactions, such as websocket requests, create a custom transaction. Creating a custom transaction gives you the same type of visibility into that custom transaction that you would get from a transaction that the agent automatically instruments. - -1. Wrap the handler you want to instrument with [`createWebTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createWebTransaction). -2. Ensure you call [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) at the end of the transaction. - - - Do not use brackets `[suffix]` at the end of your transaction name. New Relic automatically strips brackets from the name. Instead, use parentheses `(suffix)` or other symbols if needed. - - - - - This example instruments a `/websocket/ping` transaction and a `/websocket/new-message` transaction within **socket.io**. The `/ping` example is synchronous, while the `/new-message` example is asynchronous. - - ```js - var nr = require('newrelic'); - var app = require('http').createServer(); - var io = require('socket.io')(app); - - io.on('connection', function (socket) { - socket.on('ping', nr.createWebTransaction('/websocket/ping', function (data) { - socket.emit('pong'); - nr.endTransaction(); - })); - socket.on('new-message', nr.createWebTransaction('/websocket/new-message', function (data) { - addMessageToChat(data, function () { - socket.emit('message-received'); - nr.endTransaction(); - }); - })); - }); - ``` - - - Ensure you call [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) at the end of the transaction. - - - - -## Instrumenting background transactions [#background-txn] - -You can also use custom transactions to instrument background tasks, such as periodic jobs within your app or work that continues after a request completes. To instrument background tasks, wrap the handler you want to instrument with [`createBackgroundTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createBackgroundTransaction). Ensure you call [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) at the end of the transaction. - - - - This example instruments `update:cache` within `setInterval`: - - ```js - var nr = require('newrelic'); - var redis = require('redis').createClient(); - - setInterval(nr.createBackgroundTransaction('update:cache', function () { - var newValue = someDataGenerator(); - - redis.set('some:cache:key', newValue, function () { - nr.endTransaction(); // End the transaction once redis is done - }); - }), 30000); // Every 30s - ``` - - - Ensure you call [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) at the end of the transaction. - - - - -## Expanding instrumentation within transactions [#expanding-instrumentation] - -You can also use custom instrumentation to provide more visibility into web transactions that are already instrumented, or to gain insight into databases and other in-transaction work that is not automatically instrumented. To do this, wrap your callbacks in custom tracers. Custom tracers create and collect specific metrics for an additional segment within an existing transaction, such as a particular function or a database call. - -To instrument callbacks, wrap the callback with [`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer). If you want to instrument a function that is called inside an asynchronous function, you need to wrap both the target function and its parent asynchronous function with [`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer). - - - You must place these examples inside an already instrumented transaction. The transaction can be automatically instrumented, or via a custom transaction. - - - - - This examples wraps a single callback: - - ```js - // Wrap the callback in a segment - db.createObject(nr.createTracer('db:createObject', function (err, result) { - // Some error handler that will end the response for us - if (util.handleError(err, res)) { - return; - } - res.write(JSON.stringify(result.rows[0].id)); - res.write('\n'); - res.end(); - })); - ``` - - - - This example wraps both `pg.connect` and `client.query`. This is because `client.query` is called by an asynchronous parent function (`pg.connect`). Otherwise, we would not get any data from `client.query`. This allows `createTracer()` to propagate the active transaction across those asynchronous boundaries. - - ```js - pg.connect(config.db_string, nr.createTracer('pg:connect', function (err, client, done) { - if (util.handleError(err, '500', res)) { - return done(); - } - client.query('SELECT count(*) FROM test_count', nr.createTracer('pg:query', function (err, result) { - if (util.handleError(err, '500', res)) { - return done(); - } - - res.write(result.rows[0].count); - res.write('\n'); - })); - })); - ``` - - diff --git a/src/content/docs/apm/agents/nodejs-agent/getting-started/apm-agent-security-nodejs.mdx b/src/content/docs/apm/agents/nodejs-agent/getting-started/apm-agent-security-nodejs.mdx index 2994379fcff..f94334b57d4 100644 --- a/src/content/docs/apm/agents/nodejs-agent/getting-started/apm-agent-security-nodejs.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/getting-started/apm-agent-security-nodejs.mdx @@ -40,8 +40,8 @@ When you [enable high-security mode](/docs/agents/nodejs-agent/installation-conf If you need different security settings than default or high-security mode, you can customize these settings: * [Node.js agent configuration file](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration) -* [Custom attributes](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api#add-custom-param) -* [Node.js agent API](/docs/agents/nodejs-agent/api-guides/guide-using-nodejs-agent-api) +* [Custom attributes](https://newrelic.github.io/node-newrelic/API.html#addCustomAttribute) +* [Node.js agent API]()https://newrelic.github.io/node-newrelic/API.html) diff --git a/src/content/docs/apm/agents/nodejs-agent/getting-started/compatibility-requirements-nodejs-agent.mdx b/src/content/docs/apm/agents/nodejs-agent/getting-started/compatibility-requirements-nodejs-agent.mdx index 429ea5d2c70..7e2e8924ea7 100644 --- a/src/content/docs/apm/agents/nodejs-agent/getting-started/compatibility-requirements-nodejs-agent.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/getting-started/compatibility-requirements-nodejs-agent.mdx @@ -12,7 +12,7 @@ redirects: freshnessValidatedDate: never --- -Our Node.js agent includes built-in instrumentation of the most popular Node.js frameworks, app servers, databases, and message queuing systems. For frameworks and libraries that aren't instrumented out of the box, you can extend the agent with our [Node.js agent API](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/). +Our Node.js agent includes built-in instrumentation of the most popular Node.js frameworks, app servers, databases, and message queuing systems. For frameworks and libraries that aren't instrumented out of the box, you can extend the agent with our [Node.js agent API](https://newrelic.github.io/node-newrelic/API.html). Our Node.js agent is publicly available on the [Node Package Manager (npm) repository](https://npmjs.org/package/newrelic) as well as on [GitHub](https://github.com/newrelic/node-newrelic). Ready to try out New Relic's Node.js agent? [Create a New Relic account](https://newrelic.com/signup)! diff --git a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/distributed-tracing-nodejs-agent.mdx b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/distributed-tracing-nodejs-agent.mdx index fb78619209a..9fc5e1e7191 100644 --- a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/distributed-tracing-nodejs-agent.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/distributed-tracing-nodejs-agent.mdx @@ -210,13 +210,14 @@ If a service is not passing the trace header to other services, you can use the To instrument the calling service: 1. Ensure the [version of the APM agent](#compatibility-requirements) that monitors the calling service supports distributed tracing. - 2. Invoke the agent API call for generating a distributed trace payload (see the [Node.js agent API](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api#transaction-handle-createDistributedTracePayload). + 2. Invoke the agent API call for generating a distributed trace payload (see the [Node.js agent API](https://newrelic.github.io/node-newrelic/TransactionHandle.html#insertDistributedTraceHeaders)). To maintain proper ordering of spans in a trace, ensure you **generate the payload in the context of the span that sends it**. 3. Add that payload to the call made to the destination service (for example, in a header). - 4. (Optional) Identify the call as an external call (see the [Node.js agent API](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api#custom-instrumentation-api). + + For more information, see the [distributed tracing example application](https://github.com/newrelic/newrelic-node-examples/tree/0a036fd669b4b47b8afbc7add8696980f799f0da/custom-instrumentation/distributed-tracing) on GitHub. diff --git a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/es-modules.mdx b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/es-modules.mdx index fb3ce0dc6f3..81ac84716bd 100644 --- a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/es-modules.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/es-modules.mdx @@ -89,10 +89,10 @@ node --experimental-loader newrelic/esm-loader.mjs -r newrelic your-program.js ## Custom instrumentation [#custom-instrumentation] The Node.js APM agent supports adding custom instrumentation to your ES module applications. -You can create instrumentation in ES module applications using most of the [instrumentation registration methods on the API](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#custom-instrumentation-api). +You can create instrumentation in ES module applications using most of the [instrumentation registration methods on the API](https://newrelic.github.io/node-newrelic/API.html#instrument). Due to the nature of ES module imports, we are unable to support `newrelic.instrumentLoadedModule`. ES module bindings are not assignable, which prevent the agent from replacing a module's exported members with instrumentation after the module has been loaded. -To see a demonstration of how to use the custom instrumentation API in an ES module application, check out our [example](https://github.com/newrelic/newrelic-node-examples/blob/main/esm-app/custom-instrumentation/index.js) in GitHub. +To see a demonstration of how to use the custom instrumentation API in an ES module application, check out our [example](https://github.com/newrelic/newrelic-node-examples/blob/4284ee7eab69708238db0a44f97ff7e839e165cf/esm-app/custom-instrumentation/index.js) in GitHub. ## Learn More [#learn-more] diff --git a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/install-nodejs-agent.mdx b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/install-nodejs-agent.mdx index 135933821e3..59a2007a23e 100644 --- a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/install-nodejs-agent.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/install-nodejs-agent.mdx @@ -98,7 +98,7 @@ To install the Node.js agent: If you are unable to use the `-r` require flag you can also use `require('newrelic')` as the first line of your app's main module. **Note** If you are using [Babel](https://babeljs.io/docs/en/index.html) or a similar transpiler `require('newrelic')` will cause instrumentation issues. - If neither of these options work for you, (e.g. asynchronously loading api keys from a remote location during application bootstrapping), you may also add stock instrumentation to an already loaded [supported module](https://github.com/newrelic/node-newrelic/blob/0113eb5f0e707dc662a17d262a841503bab88841/lib/instrumentations.js#L6#L6) by using [`newrelic.instrumentLoadedModule`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#instrumentLoadedModule): + If neither of these options work for you, (for example, asynchronously loading API keys from a remote location during application bootstrapping), you may also add stock instrumentation to an already loaded [supported module](https://github.com/newrelic/node-newrelic/blob/0113eb5f0e707dc662a17d262a841503bab88841/lib/instrumentations.js#L6#L6) by using [`newrelic.instrumentLoadedModule`](https://newrelic.github.io/node-newrelic/API.html#instrumentLoadedModule): ```js // module loaded before newrelic @@ -121,7 +121,7 @@ To install the Node.js agent: You can further [customize your agent behavior](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration) via `newrelic.js` or an environment variable. To keep the agent configuration separate from your app, edit the [`NEW_RELIC_HOME` environmental variable](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration#home). -For more information, see our [API doc](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/). +For more information, see our [API doc](https://newrelic.github.io/node-newrelic/API.html). diff --git a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration.mdx b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration.mdx index aab4fc335d2..bde49cf0376 100644 --- a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration.mdx @@ -1284,7 +1284,7 @@ This section allows you to choose which API methods are enabled. Each configurat
- This option enables [`newrelic.noticeError`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#noticeError). + This option enables [`newrelic.noticeError`](https://newrelic.github.io/node-newrelic/API.html#noticeError). @@ -1569,7 +1569,7 @@ You can [manage how error are handled](/docs/agents/manage-apm-agents/agent-data Comma-delimited list of HTTP status codes for the error collector to ignore. - Errors recorded using [`newrelic.noticeError()`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#noticeError) do not obey this configuration value. + Errors recorded using [`newrelic.noticeError()`](https://newrelic.github.io/node-newrelic/API.html#noticeError) do not obey this configuration value. @@ -1625,7 +1625,7 @@ You can [manage how error are handled](/docs/agents/manage-apm-agents/agent-data Would ignore all reference errors. - Errors recorded using [`newrelic.noticeError()`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#noticeError) do not obey this configuration value. + Errors recorded using [`newrelic.noticeError()`](https://newrelic.github.io/node-newrelic/API.html#noticeError) do not obey this configuration value. @@ -1679,7 +1679,7 @@ You can [manage how error are handled](/docs/agents/manage-apm-agents/agent-data Would ignore all errors of type `Error`, with the exact (case-sensitive) message strings of `Undefined` and `Out of time`. - Errors recorded using [`newrelic.noticeError()`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#noticeError) do not obey this configuration value. + Errors recorded using [`newrelic.noticeError()`](https://newrelic.github.io/node-newrelic/API.html#noticeError) do not obey this configuration value. @@ -1724,7 +1724,7 @@ You can [manage how error are handled](/docs/agents/manage-apm-agents/agent-data Comma-delimited list of HTTP status codes for the error collector to mark as expected. - Errors recorded using [`newrelic.noticeError()`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#noticeError) do not obey this configuration value. + Errors recorded using [`newrelic.noticeError()`](https://newrelic.github.io/node-newrelic/API.html#noticeError) do not obey this configuration value. @@ -1778,7 +1778,7 @@ You can [manage how error are handled](/docs/agents/manage-apm-agents/agent-data Would mark all reference errors as expected. - Errors recorded using [`newrelic.noticeError()`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#noticeError) do not obey this configuration value. + Errors recorded using [`newrelic.noticeError()`](https://newrelic.github.io/node-newrelic/API.html#noticeError) do not obey this configuration value. @@ -1832,7 +1832,7 @@ You can [manage how error are handled](/docs/agents/manage-apm-agents/agent-data Would mark all errors of type `Error`, with the exact (case-sensitive) message strings of `Undefined` and `Out of time`. - Errors recorded using [`newrelic.noticeError()`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#noticeError) do not obey this configuration value. + Errors recorded using [`newrelic.noticeError()`](https://newrelic.github.io/node-newrelic/API.html#noticeError) do not obey this configuration value. @@ -3716,7 +3716,7 @@ The `grpc` section controls the behavior of how the gRPC server is instrumented. Comma-delimited list of gRPC status codes for the error collector to ignore, both on client-side and server-side instrumentation. - Errors recorded using [`newrelic.noticeError()`](/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api/#noticeError) do not obey this configuration value. + Errors recorded using [`newrelic.noticeError()`](https://newrelic.github.io/node-newrelic/API.html#noticeError) do not obey this configuration value. diff --git a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/update-nodejs-agent.mdx b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/update-nodejs-agent.mdx index fbc72b089d0..00b85e0ffc0 100644 --- a/src/content/docs/apm/agents/nodejs-agent/installation-configuration/update-nodejs-agent.mdx +++ b/src/content/docs/apm/agents/nodejs-agent/installation-configuration/update-nodejs-agent.mdx @@ -465,7 +465,7 @@ Before upgrading to Node.js version 7, review this information for major changes * **v5 - v6:** Starting in agent v5.0.0, this method was marked as deprecated but left in to give a transition period for the new methods. - * **v7:** Applications must use the API method [`transactionHandle.ignore()`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api/#transaction-handle-ignore). + * **v7:** Applications must use the API method [`transactionHandle.ignore()`](https://newrelic.github.io/node-newrelic/TransactionHandle.html#ignore). @@ -475,7 +475,7 @@ Before upgrading to Node.js version 7, review this information for major changes - * Applications must use the configuration [`api.custom_attributes_enabled` or the associated environment variable `NEW_RELIC_API_CUSTOM_ATTRIBUTES`](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration/#custom-attributes) to enable [`newrelic.addCustomAttribute`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api/#add-custom-attribute) and [`newrelic.addCustomAttributes`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api/#add-custom-attributes). + * To enable [`newrelic.addCustomAttribute`](https://newrelic.github.io/node-newrelic/API.html#addCustomAttribute) and [`newrelic.addCustomAttributes`](https://newrelic.github.io/node-newrelic/API.html#addCustomAttributes), applications must use the configuration [`api.custom_attributes_enabled` or the associated environment variable `NEW_RELIC_API_CUSTOM_ATTRIBUTES`](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration/#custom-attributes). @@ -486,8 +486,8 @@ Before upgrading to Node.js version 7, review this information for major changes * **v6.4.0-v6.14.0:** Starting in agent v6.4.0, these method were marked as deprecated but left in to give a transition period for the new methods. - * **v7:** Applications must use the API methods [`transactionHandle.insertDistributedTraceHeaders(headers)`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api/#transaction-handle-insertDistributedTraceHeaders) and [`transactionHandle.acceptDistributedTraceHeaders(transportType, headers) - `](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api/#transaction-handle-acceptDistributedTraceHeaders). With these methods, the Node.js agent will now accept W3C's `traceparent` and `tracestate` headers when calling `transactionHandle.acceptDistributedTraceHeaders(headers)` and include the W3C headers along with the New Relic distributed tracing header when calling `transactionHandle.insertDistributedTraceHeaders(headers)`, unless the New Relic trace header format is disabled using [`distributed_tracing.exclude_newrelic_header:true`.](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration/#dt-exclude-newrelic-header) + * **v7:** Applications must use the API methods [`transactionHandle.insertDistributedTraceHeaders(headers)`](https://newrelic.github.io/node-newrelic/TransactionHandle.html#insertDistributedTraceHeaders) and [`transactionHandle.acceptDistributedTraceHeaders(transportType, headers) + `](https://newrelic.github.io/node-newrelic/TransactionHandle.html#acceptDistributedTraceHeaders). With these methods, the Node.js agent will now accept W3C's `traceparent` and `tracestate` headers when calling `transactionHandle.acceptDistributedTraceHeaders(headers)` and include the W3C headers along with the New Relic distributed tracing header when calling `transactionHandle.insertDistributedTraceHeaders(headers)`, unless the New Relic trace header format is disabled using [`distributed_tracing.exclude_newrelic_header:true`.](/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration/#dt-exclude-newrelic-header) @@ -607,7 +607,7 @@ Before upgrading to Node.js agent v5, review this information for major changes. * **v2 - v4:** Starting in agent v2.7.0, these methods were marked as deprecated but left in to give a transition period for the new methods. - * **v5:** Applications must use the API methods [`newrelic.addCustomAttribute()`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api#add-custom-attribute) and [`newrelic.addCustomAttributes()`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api#add-custom-attributes). These are drop-in replacements for the old methods. + * **v5:** Applications must use the API methods [`newrelic.addCustomAttribute()`](https://newrelic.github.io/node-newrelic/API.html#addCustomAttribute) and [`newrelic.addCustomAttributes()`](https://newrelic.github.io/node-newrelic/API.html#addCustomAttributes). These are drop-in replacements for the old methods. @@ -618,7 +618,7 @@ Before upgrading to Node.js agent v5, review this information for major changes. * **v2 - v4:** Starting in agent v2.0.2, these methods were marked as deprecated but left in to give a transition period to the new methods. - * **v5:** Applications must update to the API methods [`newrelic.startWebTransaction()`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api#startWebTransaction) and [`newrelic.startBackgroundTransaction()`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api#startBackgroundTransaction). + * **v5:** Applications must update to the API methods [`newrelic.startWebTransaction()`](https://newrelic.github.io/node-newrelic/API.html#startWebTransaction) and [`newrelic.startBackgroundTransaction()`](https://newrelic.github.io/node-newrelic/API.html#startBackgroundTransaction). * **Troubleshooting tips:** These new methods are **not** drop-in replacements for the old ones. Before moving to these new methods, review our [custom instrumentation guide](/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation#web-txn). @@ -630,7 +630,7 @@ Before upgrading to Node.js agent v5, review this information for major changes. * **v3 - v4:** Starting in agent v3.3.0, this method was marked as deprecated in favor of `newrelic.startSegment()`. - * **v5:** Applications must update to [`newrelic.startSegment()`](/docs/agents/nodejs-agent/api-guides/nodejs-agent-api#startSegment). + * **v5:** Applications must update to [`newrelic.startSegment()`](https://newrelic.github.io/node-newrelic/API.html#startSegment). @@ -963,7 +963,7 @@ Before upgrading to Node.js agent v2, review this information for major changes. id="newrelic_instrument" title={<>newrelic.instrument()newrelic.instrumentDatastore()newrelic.instrumentWebframework()newrelic.instrumentMessages()} > - Use these methods to add custom instrumentation for third party modules, including those already instrumented by the New Relic Node.js agent. For more information, see New Relic's [Node.js instrumentation tutorials on GitHub](https://newrelic.github.io/node-newrelic/tutorial-Instrumentation-Basics.html). + Use these methods to add custom instrumentation for third party modules, including those already instrumented by the New Relic Node.js agent. For more information, see New Relic's [Node.js instrumentation example application on GitHub](https://github.com/newrelic/newrelic-node-examples/tree/4284ee7eab69708238db0a44f97ff7e839e165cf/custom-instrumentation/instrument). - No utilice corchetes `[suffix]` al final del nombre de su transacción. New Relic elimina automáticamente los corchetes del nombre. En su lugar, utilice paréntesis `(suffix)` u otros símbolos si es necesario. - - - - - Este ejemplo instrumentó una transacción `/websocket/ping` y una transacción `/websocket/new-message` dentro de **socket.io**. El ejemplo `/ping` es sincrónico, mientras que el ejemplo `/new-message` es asincrónico. - - ```js - var nr = require('newrelic'); - var app = require('http').createServer(); - var io = require('socket.io')(app); - - io.on('connection', function (socket) { - socket.on('ping', nr.createWebTransaction('/websocket/ping', function (data) { - socket.emit('pong'); - nr.endTransaction(); - })); - socket.on('new-message', nr.createWebTransaction('/websocket/new-message', function (data) { - addMessageToChat(data, function () { - socket.emit('message-received'); - nr.endTransaction(); - }); - })); - }); - ``` - - - Asegúrese de llamar [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) al final de la transacción. - - - - -## Instrumentado fondo transacción [#background-txn] - -También puede utilizar transacciones personalizadas para instrumentar tareas en segundo plano, como trabajos periódicos dentro de su aplicación o trabajos que continúan después de que se completa una solicitud. Para instrumentar tareas en segundo plano, ajuste el controlador con el que desea instrumentar [`createBackgroundTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createBackgroundTransaction). Asegúrese de llamar [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) al final de la transacción. - - - - Este ejemplo instrumentó `update:cache` dentro de `setInterval`: - - ```js - var nr = require('newrelic'); - var redis = require('redis').createClient(); - - setInterval(nr.createBackgroundTransaction('update:cache', function () { - var newValue = someDataGenerator(); - - redis.set('some:cache:key', newValue, function () { - nr.endTransaction(); // End the transaction once redis is done - }); - }), 30000); // Every 30s - ``` - - - Asegúrese de llamar [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) al final de la transacción. - - - - -## Ampliando la instrumentación dentro de transacción [#expanding-instrumentation] - -También puede utilizar instrumentación personalizada para proporcionar más visibilidad a las transacciones web que ya están instrumentadas, o para obtener información valiosa sobre la base de datos y otros trabajos en transacción que no se instrumentan automáticamente. Para hacer esto, envuelva su devolución de llamada en un rastreador personalizado. El rastreador personalizado crea y recopila métricas específicas para un segmento adicional dentro de una transacción existente, como una función particular o una llamada a una base de datos. - -Para realizar devoluciones de llamada, envuelva la devolución de llamada con [`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer). Si desea instrumentar una función que se llama dentro de una función asincrónica, debe envolver tanto la función objetivo como su función asincrónica principal con [`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer). - - - Debes colocar estos ejemplos dentro de una transacción ya instrumentada. La transacción puede instrumentarse automáticamente o mediante una transacción personalizada. - - - - - Este ejemplo incluye una única devolución de llamada: - - ```js - // Wrap the callback in a segment - db.createObject(nr.createTracer('db:createObject', function (err, result) { - // Some error handler that will end the response for us - if (util.handleError(err, res)) { - return; - } - res.write(JSON.stringify(result.rows[0].id)); - res.write('\n'); - res.end(); - })); - ``` - - - - Este ejemplo incluye tanto `pg.connect` como `client.query`. Esto se debe a que `client.query` es llamado por una función principal asincrónica (`pg.connect`). De lo contrario, no obtendríamos ningún dato de `client.query`. Esto permite a `createTracer()` propagar la transacción activa a través de esos límites asincrónicos. - - ```js - pg.connect(config.db_string, nr.createTracer('pg:connect', function (err, client, done) { - if (util.handleError(err, '500', res)) { - return done(); - } - client.query('SELECT count(*) FROM test_count', nr.createTracer('pg:query', function (err, result) { - if (util.handleError(err, '500', res)) { - return done(); - } - - res.write(result.rows[0].count); - res.write('\n'); - })); - })); - ``` - - diff --git a/src/i18n/content/jp/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx b/src/i18n/content/jp/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx deleted file mode 100644 index 4ea7094cb4c..00000000000 --- a/src/i18n/content/jp/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Node.js v1 カスタム・インスツルメンテーション(レガシー) -tags: - - Agents - - Nodejs agent - - Extend your instrumentation -metaDescription: 'Expand your Node.js instrumentation in New Relic to cover uninstrumented frameworks, databases, segments. Use custom tracers to better track async work.' -freshnessValidatedDate: never -translationType: machine ---- - -New Relic for Node.js は、ほとんどの標準的な Web リクエストを自動的にインスツルメンテーションしますが、時には拡張インスツルメンテーションが必要な場合もあります。カスタムインスツルメンテーションでは、 [ウェブソケット](#web-txn) 、 [バックグラウンドジョブ](#background-txn) 、 [サポートされていないデータベース](#expanding-instrumentation) をインスツルメンテーションすることができます。また、カスタムインスツルメンテーションでは、 [コードの特定のセクションをターゲットにして、より深い洞察を得ることができます。](#expanding-instrumentation) 。 - -カスタム・インスツルメンテーションは、Node.jsエージェントのバージョン1.10.0以降で利用可能です。最新の Node.js エージェントの機能を利用するには、 [エージェントをアップグレードしてください](/docs/agents/nodejs-agent/installation-configuration/upgrade-nodejs-agent) 。 - -## Webトランザクションのインストゥルメンテーション [#web-txn] - -WebsocketリクエストなどのWebトランザクションを計測するには、カスタムトランザクションを作成します。カスタムトランザクションを作成すると、エージェントが自動的に計測するトランザクションと同じ種類の可視性が得られます。 - -1. インストルメントするハンドラーを[`createWebTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createWebTransaction)でラップします。 -2. トランザクションの最後に必ず[`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction)に電話してください。 - - - トランザクション名の末尾に角かっこ`[suffix]`を使用しないでください。 New Relicは、名前から角かっこを自動的に削除します。代わりに、必要に応じて括弧`(suffix)`またはその他の記号を使用してください。 - - - - - この例のインストゥルメントは、 **socket.io**内で`/websocket/ping`トランザクションと`/websocket/new-message`トランザクションが実行されました。 `/ping`例は同期ですが、 `/new-message`例は非同期です。 - - ```js - var nr = require('newrelic'); - var app = require('http').createServer(); - var io = require('socket.io')(app); - - io.on('connection', function (socket) { - socket.on('ping', nr.createWebTransaction('/websocket/ping', function (data) { - socket.emit('pong'); - nr.endTransaction(); - })); - socket.on('new-message', nr.createWebTransaction('/websocket/new-message', function (data) { - addMessageToChat(data, function () { - socket.emit('message-received'); - nr.endTransaction(); - }); - })); - }); - ``` - - - トランザクションの最後に必ず[`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction)に電話してください。 - - - - -## バックグラウンド・トランザクションのインストゥルメンテーション [#background-txn] - -カスタムトランザクションを使用して、アプリ内の定期的なジョブやリクエストの完了後に継続する作業などのバックグラウンドタスクを計測することもできます。バックグラウンドタスクをインストルメントするには、インストルメントするハンドラーを[`createBackgroundTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createBackgroundTransaction)でラップします。トランザクションの最後に[`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction)を呼び出すようにしてください。 - - - - この例では、 `setInterval` }内の`update:cache`を計測します。 - - ```js - var nr = require('newrelic'); - var redis = require('redis').createClient(); - - setInterval(nr.createBackgroundTransaction('update:cache', function () { - var newValue = someDataGenerator(); - - redis.set('some:cache:key', newValue, function () { - nr.endTransaction(); // End the transaction once redis is done - }); - }), 30000); // Every 30s - ``` - - - トランザクションの最後に必ず[`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction)に電話してください。 - - - - -## トランザクション内でのインストゥルメンテーションの拡大 [#expanding-instrumentation] - -また、カスタム・インスツルメンテーションを使用して、すでにインスツルメンテーションされているウェブ・トランザクションの可視性を高めたり、自動的にインスツルメンテーションされていないデータベースやその他のトランザクション内の作業を把握したりすることもできます。そのためには、コールバックをカスタムトレーサーでラップします。カスタムトレーサーは、特定の関数やデータベースの呼び出しなど、既存のトランザクション内の追加セグメントに対して特定のメトリクスを作成し、収集します。 - -コールバックをインストルメント化するには、コールバックを[`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer)でラップします。非同期関数内で呼び出される関数をインストルメント化する場合は、ターゲット関数とその親非同期関数の両方を[`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer)でラップする必要があります。 - - - これらのサンプルは、すでにインスツルメンテーションされているトランザクションの中に置かなければなりません。トランザクションは、自動的にインスツルメンテーションされるか、カスタム・トランザクションを介してインスツルメンテーションされます。 - - - - - この例では、1つのコールバックをラップしています。 - - ```js - // Wrap the callback in a segment - db.createObject(nr.createTracer('db:createObject', function (err, result) { - // Some error handler that will end the response for us - if (util.handleError(err, res)) { - return; - } - res.write(JSON.stringify(result.rows[0].id)); - res.write('\n'); - res.end(); - })); - ``` - - - - この例では、 `pg.connect`と`client.query`の両方をラップしています。これは、 `client.query`が非同期の親関数( `pg.connect` )によって呼び出されるためです。そうしないと、 `client.query`からデータを取得できません。これにより、 `createTracer()`はアクティブなトランザクションをこれらの非同期境界を越えて伝播できます。 - - ```js - pg.connect(config.db_string, nr.createTracer('pg:connect', function (err, client, done) { - if (util.handleError(err, '500', res)) { - return done(); - } - client.query('SELECT count(*) FROM test_count', nr.createTracer('pg:query', function (err, result) { - if (util.handleError(err, '500', res)) { - return done(); - } - - res.write(result.rows[0].count); - res.write('\n'); - })); - })); - ``` - - diff --git a/src/i18n/content/kr/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx b/src/i18n/content/kr/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx deleted file mode 100644 index 314e780c915..00000000000 --- a/src/i18n/content/kr/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Node.js v1 사용자 정의 계측(레거시) -tags: - - Agents - - Nodejs agent - - Extend your instrumentation -metaDescription: 'Expand your Node.js instrumentation in New Relic to cover uninstrumented frameworks, databases, segments. Use custom tracers to better track async work.' -freshnessValidatedDate: never -translationType: machine ---- - -New Relic for Node.js는 대부분의 표준 웹 요청을 자동으로 계측하지만 때로는 확장된 계측을 원할 때도 있습니다. 사용자 정의 계측을 사용하여 [웹 소켓](#web-txn) , [백그라운드 작업](#background-txn) 및 [지원되지 않는 데이터베이스](#expanding-instrumentation) 를 계측할 수 있습니다. 사용자 정의 계측은 [더 깊은 통찰력을 위해 코드의 특정 섹션을 대상으로](#expanding-instrumentation) 할 수도 있습니다. - -사용자 정의 계측은 Node.js 에이전트 버전 1.10.0 이상에서 사용할 수 있습니다. 최신 Node.js 에이전트 기능을 활용하려면 에이전트를 [업그레이드하십시오](/docs/agents/nodejs-agent/installation-configuration/upgrade-nodejs-agent) . - -## 웹 트랜잭션 계측 [#web-txn] - -websocket 요청과 같은 웹 트랜잭션을 계측하려면 사용자 지정 트랜잭션을 생성하십시오. 사용자 지정 트랜잭션을 생성하면 에이전트가 자동으로 계측하는 트랜잭션에서 얻을 수 있는 것과 동일한 유형의 사용자 지정 트랜잭션에 대한 가시성을 얻을 수 있습니다. - -1. 계측하려는 핸들러를 [`createWebTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createWebTransaction) 으로 래핑합니다. -2. 트랜잭션이 끝날 때 [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) 을(를) 호출해야 합니다. - - - 거래 이름 끝에 대괄호 `[suffix]` 를 사용하지 마십시오. New Relic은 자동으로 이름에서 괄호를 제거합니다. 대신 필요한 경우 괄호 `(suffix)` 또는 기타 기호를 사용하십시오. - - - - - 이 예는 **socket.io** 내에 있는 `/websocket/ping` RX 및 `/websocket/new-message` RX입니다. `/ping` 예시는 동기식인 반면, `/new-message` 예시는 비동기식입니다. - - ```js - var nr = require('newrelic'); - var app = require('http').createServer(); - var io = require('socket.io')(app); - - io.on('connection', function (socket) { - socket.on('ping', nr.createWebTransaction('/websocket/ping', function (data) { - socket.emit('pong'); - nr.endTransaction(); - })); - socket.on('new-message', nr.createWebTransaction('/websocket/new-message', function (data) { - addMessageToChat(data, function () { - socket.emit('message-received'); - nr.endTransaction(); - }); - })); - }); - ``` - - - 트랜잭션이 끝날 때 [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) 을(를) 호출해야 합니다. - - - - -## 백그라운드 트랜잭션 계측 [#background-txn] - -또한 사용자 지정 트랜잭션을 사용하여 앱 내의 주기적 작업 또는 요청이 완료된 후 계속되는 작업과 같은 백그라운드 작업을 계측할 수 있습니다. 백그라운드 작업을 계측하려면 계측하려는 핸들러를[`createBackgroundTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createBackgroundTransaction) 으로 래핑합니다. 트랜잭션이 끝날 때 [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) 을(를) 호출해야 합니다. - - - - 이 예시는 `setInterval` } 내에서 `update:cache` 를 계측합니다. - - ```js - var nr = require('newrelic'); - var redis = require('redis').createClient(); - - setInterval(nr.createBackgroundTransaction('update:cache', function () { - var newValue = someDataGenerator(); - - redis.set('some:cache:key', newValue, function () { - nr.endTransaction(); // End the transaction once redis is done - }); - }), 30000); // Every 30s - ``` - - - 트랜잭션이 끝날 때 [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) 을(를) 호출해야 합니다. - - - - -## 트랜잭션 내 계측 확장 [#expanding-instrumentation] - -또한 사용자 지정 계측을 사용하여 이미 계측된 웹 트랜잭션에 대한 가시성을 높이거나 자동으로 계측되지 않는 데이터베이스 및 기타 트랜잭션 내 작업에 대한 통찰력을 얻을 수 있습니다. 이렇게 하려면 사용자 지정 추적 프로그램에서 콜백을 래핑합니다. 사용자 지정 추적기는 특정 기능 또는 데이터베이스 호출과 같은 기존 트랜잭션 내의 추가 세그먼트에 대한 특정 메트릭을 생성하고 수집합니다. - -콜백을 계측하려면 [`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer) 으로 콜백을 래핑합니다. 비동기 함수 내에서 호출되는 함수를 계측하려면 대상 함수와 상위 비동기 함수를 [`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer) 로 래핑해야 합니다. - - - 이미 계측된 트랜잭션 내부에 이러한 예제를 배치해야 합니다. 트랜잭션은 자동으로 계측되거나 사용자 지정 트랜잭션을 통해 수행될 수 있습니다. - - - - - 이 예에서는 단일 콜백을 래핑합니다. - - ```js - // Wrap the callback in a segment - db.createObject(nr.createTracer('db:createObject', function (err, result) { - // Some error handler that will end the response for us - if (util.handleError(err, res)) { - return; - } - res.write(JSON.stringify(result.rows[0].id)); - res.write('\n'); - res.end(); - })); - ``` - - - - 이 예는 `pg.connect` 및 `client.query` 모두를 래핑합니다. 이는 `client.query` 가 비동기 상위 함수( `pg.connect` )에 의해 호출되기 때문입니다. 그렇지 않으면 `client.query` 에서 데이터를 얻을 수 없습니다. 이렇게 하면 `createTracer()` 가 이러한 비동기 경계를 넘어 활성 트랜잭션을 전파할 수 있습니다. - - ```js - pg.connect(config.db_string, nr.createTracer('pg:connect', function (err, client, done) { - if (util.handleError(err, '500', res)) { - return done(); - } - client.query('SELECT count(*) FROM test_count', nr.createTracer('pg:query', function (err, result) { - if (util.handleError(err, '500', res)) { - return done(); - } - - res.write(result.rows[0].count); - res.write('\n'); - })); - })); - ``` - - diff --git a/src/i18n/content/pt/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx b/src/i18n/content/pt/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx deleted file mode 100644 index 50ac4324e10..00000000000 --- a/src/i18n/content/pt/docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy.mdx +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Node.js v1 instrumentação personalizada (legado) -tags: - - Agents - - Nodejs agent - - Extend your instrumentation -metaDescription: 'Expand your Node.js instrumentation in New Relic to cover uninstrumented frameworks, databases, segments. Use custom tracers to better track async work.' -freshnessValidatedDate: never -translationType: machine ---- - -O New Relic para Node.js instrumenta automaticamente a maioria das solicitações padrão da web, mas às vezes você deseja instrumentação expandida. Com instrumentação personalizada, você pode instrumentar [web sockets](#web-txn), [trabalhos em segundo plano](#background-txn) e [bancos de dados não suportados](#expanding-instrumentation). A instrumentação personalizada também pode [direcionar seções específicas do seu código para uma visão mais profunda](#expanding-instrumentation). - -A instrumentação personalizada está disponível nas versões 1.10.0 ou superior do agente Node.js. Para aproveitar as vantagens do recurso de agente Node.js mais recente, [atualize seu agente](/docs/agents/nodejs-agent/installation-configuration/upgrade-nodejs-agent). - -## Transação instrumentada da web [#web-txn] - -Para instrumentos de transação da web, como solicitações de websocket, crie uma transação personalizada. A criação de uma transação personalizada oferece o mesmo tipo de visibilidade dessa transação personalizada que você obteria de uma transação que o agente instrumentou automaticamente. - -1. Envolva o manipulador que você deseja instrumento com [`createWebTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createWebTransaction). -2. Certifique-se de chamar [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) no final da transação. - - - Não use colchetes `[suffix]` no final do nome da sua transação. O New Relic remove automaticamente os colchetes do nome. Em vez disso, use parênteses `(suffix)` ou outros símbolos, se necessário. - - - - - Este exemplo instrumento uma transação `/websocket/ping` e uma transação `/websocket/new-message` dentro de **socket.io**. O exemplo `/ping` é síncrono, enquanto o exemplo `/new-message` é assíncrono. - - ```js - var nr = require('newrelic'); - var app = require('http').createServer(); - var io = require('socket.io')(app); - - io.on('connection', function (socket) { - socket.on('ping', nr.createWebTransaction('/websocket/ping', function (data) { - socket.emit('pong'); - nr.endTransaction(); - })); - socket.on('new-message', nr.createWebTransaction('/websocket/new-message', function (data) { - addMessageToChat(data, function () { - socket.emit('message-received'); - nr.endTransaction(); - }); - })); - }); - ``` - - - Certifique-se de chamar [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) no final da transação. - - - - -## Histórico de transação instrumentado [#background-txn] - -Você também pode usar a transação personalizada para instrumentar tarefas em segundo plano, como trabalhos periódicos em seu aplicativo ou trabalhos que continuam após a conclusão de uma solicitação. Para instrumentar tarefas em segundo plano, envolva o manipulador que você deseja instrumentar com [`createBackgroundTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createBackgroundTransaction). Certifique-se de chamar [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) no final da transação. - - - - Este exemplo de instrumento `update:cache` dentro de `setInterval`: - - ```js - var nr = require('newrelic'); - var redis = require('redis').createClient(); - - setInterval(nr.createBackgroundTransaction('update:cache', function () { - var newValue = someDataGenerator(); - - redis.set('some:cache:key', newValue, function () { - nr.endTransaction(); // End the transaction once redis is done - }); - }), 30000); // Every 30s - ``` - - - Certifique-se de chamar [`endTransaction()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#endTransaction) no final da transação. - - - - -## Expandindo a instrumentação dentro da transação [#expanding-instrumentation] - -Você também pode usar instrumentação personalizada para fornecer mais visibilidade nas transações da web que já estão instrumentadas ou para obter insights sobre o banco de dados e outros trabalhos de transação que não são instrumentados automaticamente. Para fazer isso, envolva seu retorno de chamada no rastreador personalizado. O rastreador personalizado cria e coleta métricas específicas para um segmento adicional dentro de uma transação existente, como uma função específica ou uma chamada de banco de dados. - -Para retornos de chamada do instrumento, envolva o retorno da chamada com [`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer). Se você deseja instrumentar uma função que é chamada dentro de uma função assíncrono, você precisa agrupar a função alvo e sua função assíncrono pai com [`createTracer()`](/docs/agents/nodejs-agent/supported-features/nodejs-agent-api#createTracer). - - - Você deve colocar estes exemplos dentro de uma transação já instrumentada. A transação pode ser instrumentada automaticamente ou por meio de uma transação customizada. - - - - - Este exemplo envolve um único retorno de chamada: - - ```js - // Wrap the callback in a segment - db.createObject(nr.createTracer('db:createObject', function (err, result) { - // Some error handler that will end the response for us - if (util.handleError(err, res)) { - return; - } - res.write(JSON.stringify(result.rows[0].id)); - res.write('\n'); - res.end(); - })); - ``` - - - - Este exemplo envolve `pg.connect` e `client.query`. Isto ocorre porque `client.query` é chamado por uma função pai assíncrono (`pg.connect`). Caso contrário, não obteríamos nenhum dado de `client.query`. Isto permite que `createTracer()` propague a transação ativa através desses limites assíncronos. - - ```js - pg.connect(config.db_string, nr.createTracer('pg:connect', function (err, client, done) { - if (util.handleError(err, '500', res)) { - return done(); - } - client.query('SELECT count(*) FROM test_count', nr.createTracer('pg:query', function (err, result) { - if (util.handleError(err, '500', res)) { - return done(); - } - - res.write(result.rows[0].count); - res.write('\n'); - })); - })); - ``` - - diff --git a/src/nav/apm.yml b/src/nav/apm.yml index 5183ba41ff0..6700882c6bb 100644 --- a/src/nav/apm.yml +++ b/src/nav/apm.yml @@ -287,11 +287,11 @@ pages: path: /docs/apm/agents/java-agent/related-integrations pages: - title: Dropwizard integration - path: /docs/apm/agents/java-agent/related-integrations/dropwizard/dropwizard-reporter + path: /docs/apm/agents/java-agent/related-integrations/dropwizard/dropwizard-reporter - title: Kamon integration - path: /docs/apm/agents/java-agent/related-integrations/kamon/kamon-reporter + path: /docs/apm/agents/java-agent/related-integrations/kamon/kamon-reporter - title: Micrometer integration - path: /docs/apm/agents/java-agent/related-integrations/micrometer/micrometer-metrics-registry + path: /docs/apm/agents/java-agent/related-integrations/micrometer/micrometer-metrics-registry - title: Java Vert.x Event Bus integration path: /docs/apm/agents/java-agent/related-integrations/vertx/vertx-eventbus-integration - title: Java Instrumentation for Vert.x Extensions @@ -506,8 +506,6 @@ pages: path: /docs/apm/agents/nodejs-agent/extend-your-instrumentation/browser-monitoring-nodejs-agent - title: Node.js VM measurements path: /docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-vm-measurements - - title: Node.js v1 custom instrumentation - path: /docs/apm/agents/nodejs-agent/extend-your-instrumentation/nodejs-v1-custom-instrumentation-legacy - title: Attributes path: /docs/apm/agents/nodejs-agent/attributes pages: @@ -714,7 +712,7 @@ pages: path: /docs/apm/agents/php-agent/frameworks-libraries/predis-library-php - title: WordPress pages: - - title: WordPress full stack integration + - title: WordPress full stack integration path: /docs/apm/agents/php-agent/frameworks-libraries/wordpress-fullstack-integration - title: WordPress specific functionality path: /docs/apm/agents/php-agent/frameworks-libraries/wordpress-specific-functionality @@ -866,7 +864,7 @@ pages: - title: capture_request_params path: /docs/apm/agents/python-agent/python-agent-api/capturerequestparams-python-agent-api - title: current_trace_id - path: /docs/apm/agents/python-agent/python-agent-api/currenttraceid-python-agent + path: /docs/apm/agents/python-agent/python-agent-api/currenttraceid-python-agent - title: current_transaction path: /docs/apm/agents/python-agent/python-agent-api/currenttransaction-python-agent-api - title: create_distributed_trace_payload @@ -1384,4 +1382,4 @@ pages: - title: Experimental agents pages: - title: Elixir integration - path: /docs/apm/experimental-agents/elixir/elixir-open-source-agent + path: /docs/apm/experimental-agents/elixir/elixir-open-source-agent