### Install Dependencies and Enable Hooks Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Installs project dependencies. This also enables the git pre-commit hook for code formatting and linting. ```sh npm install ``` -------------------------------- ### Start a New Transaction Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use to create a custom transaction. By default, custom transactions are not managed by the agent, but can be started as managed by passing `{ managed: true }`. ```javascript const transaction = apm.startTransaction(name, type, options) ``` -------------------------------- ### Install APM RUM Agent via npm Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Install the APM RUM agent as a project dependency using npm. This is the first step for integrating the agent with JavaScript bundlers. ```bash npm install @elastic/apm-rum --save ``` -------------------------------- ### apm.startTransaction() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Starts and returns a new transaction. Transactions can be managed by the agent or unmanaged, with managed transactions automatically ending when tasks are complete. ```APIDOC ## `apm.startTransaction()` [apm-start-transaction] ```js const transaction = apm.startTransaction(name, type, options) ``` Starts and returns a new transaction. Arguments: * `name` - The name of the transaction (string). Defaults to `Unknown` * `type` - The type of the transaction (string). Defaults to `custom` * `options` - Options to modify the created transaction (object). This argument is optional. The following options are supported: * `managed` - Controls whether the transaction is managed by the agent or not. Defaults to `false`. Use this method to create a custom transaction. By default, custom transactions are not managed by the agent, however, you can start a managed transaction by passing `{ managed: true }` as the `options` argument. There are some differences between managed and unmanaged transactions: * For managed transactions, the agent keeps track of the relevant tasks during the lifetime of the transaction and automatically ends it once all of the tasks are finished. Unmanaged transactions need to be ended manually by calling the [`end`](/reference/transaction-api.md#transaction-end) method. * Managed transactions include information captured via our auto-instrumentations (e.g. XHR spans). See [Supported Technologies](/reference/supported-technologies.md) for a list of instrumentations. * There can only be one managed transaction at any given time — starting a second managed transaction will end the previous one. There are no limits for unmanaged transactions. ::::{note} This method returns `undefined` if apm is disabled or if [active](/reference/configuration.md#active) flag is set to `false` in the config. :::: ``` -------------------------------- ### Run RUM Agent Benchmarks Source: https://github.com/elastic/apm-agent-rum-js/blob/main/packages/rum/test/benchmarks/BENCHMARKS.md Execute the benchmark script to build the RUM agent, start the server, and collect performance metrics for both basic and heavy scenarios. ```bash node packages/rum/test/benchmarks/run.js ``` -------------------------------- ### Access APM Agent Instance in Vue Components (Composition API) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Access the APM agent instance within Vue components using `inject('$apm')` with the Composition API and ` ``` -------------------------------- ### apm.startSpan() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Starts and returns a new span associated with the current active transaction. Spans can be blocking and can have a specified parent ID. ```APIDOC ## `apm.startSpan()` [apm-start-span] ```js const span = apm.startSpan(name, type, options) ``` Starts and returns a new span associated with the current active transaction. Arguments: * `name` - The name of the span (string). Defaults to `Unknown` * `type` - The type of the span (string). Defaults to `custom` * `options` - The following options are supported: * `blocking` - Blocks the associated transaction from ending until this span is ended. Blocked spans automatically create an internal task. Defaults to false. * `parentId` - Parent id associated with the new span. Defaults to current transaction id * `sync` - Denotes if the span is synchronous or asynchronous. Defaults to null Blocked spans allow users to control the early closing of [managed transactions](/reference/custom-transactions.md#custom-managed-transactions) in few cases when the app contains lots of async activity which cannot be tracked by the agent. ::::{note} This method returns `undefined` if apm is disabled or if [active](/reference/configuration.md#active) flag is set to `false` in the config. :::: ``` -------------------------------- ### Install APM RUM Vue Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/packages/rum-vue/README.md Install the necessary package for integrating Elastic APM RUM into your Vue application using npm. ```bash npm install @elastic/apm-rum-vue ``` -------------------------------- ### Instrument Vue Application with APM Plugin Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Configure and install the ApmVuePlugin, providing the Vue Router instance and essential agent configuration like `serviceName`. This enables automatic capturing of page load and SPA navigation events. ```javascript import { createApp, defineComponent, h } from 'vue' import { createRouter, createWebHashHistory } from 'vue-router' import { ApmVuePlugin } from '@elastic/apm-rum-vue' import App from './App.vue' const Home = defineComponent({ render: () => h("div", {}, "home") }) const router = createRouter({ history: createWebHashHistory(), routes: [ { path: '/', component: Home } ] }) createApp(App) .use(router) .use(ApmVuePlugin, { router, config: { serviceName: 'app-name', // agent configuration } }) // app specific code .mount('#app') ``` -------------------------------- ### Use APM Plugin with Vue Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Install the ApmVuePlugin in your Vue application using `app.use()`. This requires the Vue Router instance and agent configuration. ```javascript app.use(ApmVuePlugin, options) ``` -------------------------------- ### transaction.startSpan Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Starts and returns a new custom span associated with the current transaction. Spans measure the time until span.end() is called. ```APIDOC ## `transaction.startSpan([name][, type][, options])` ### Description Start and return a new custom span associated with this transaction. ### Arguments * `name` - The name of the span (string). Defaults to `unnamed` * `type` - The type of span (string). Defaults to `custom` * `options` - The following options are supported: * `blocking` - Blocks the associated transaction from ending until this span is ended. Blocked spans automatically create an internal task. Defaults to false. * `parentId` - Parent id associated with the new span. Defaults to current transaction id * `sync` - Denotes if the span is synchronous or asynchronous. ### Request Example ```js const span = transaction.startSpan('My custom span') ``` ``` -------------------------------- ### Run Tests for a Specific Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Runs tests for a single package, specified by the SCOPE environment variable. For example, to run tests for the @elastic/apm-rum package. ```sh APM_SERVER_URL= SCOPE=@elastic/apm-rum npm run test ``` -------------------------------- ### apm.observe() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Listens for RUM agent internal events, such as transaction start and end, allowing for custom logic execution via callbacks. ```APIDOC ## `apm.observe()` [observe] ```js apm.observe(name, callback) ``` Arguments: * `name` - The name of the event. * `callback` - A callback function to execute once the event is fired. Use this method to listen for RUM agent internal events. The following events are supported for the transaction lifecycle: * `transaction:start` event is fired on every transaction start. * `transaction:end` event is fired on transaction end and before it is added to the queue to be sent to APM Server. The callback function for these events receives the corresponding transaction object as its only argument. The transaction object can be modified through methods and properties documented in [Transaction API](/reference/transaction-api.md): ```js apm.observe('transaction:start', function (transaction) { if (transaction.type === 'custom') { transaction.name = window.document.title transaction.addLabels({ 'custom-label': 'custom-value' }) } }) ``` ``` -------------------------------- ### Start a New Span Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Starts and returns a new span associated with the current active transaction. Blocked spans can control the early closing of managed transactions when the app contains lots of async activity. ```javascript const span = apm.startSpan(name, type, options) ``` -------------------------------- ### Get Current Transaction Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use this method to get the current active transaction. If there is no active transaction it will return `undefined`. ```javascript apm.getCurrentTransaction() ``` -------------------------------- ### Access APM Agent Instance in Vue Components (Options API) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Access the APM agent instance within Vue components using `this.$apm`. Start spans to measure component lifecycle timings. ```html ``` -------------------------------- ### Observe Agent Events Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use this method to listen for RUM agent internal events, such as transaction start and end. The callback function receives the transaction object, which can be modified. ```javascript apm.observe(name, callback) ``` ```javascript apm.observe('transaction:start', function (transaction) { if (transaction.type === 'custom') { transaction.name = window.document.title transaction.addLabels({ 'custom-label': 'custom-value' }) } }) ``` -------------------------------- ### Mark Transaction Point with transaction.mark(key) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Marks the current point in time relative to the start of the transaction. Use this method to mark significant events that happen while the transaction is active. Special characters in the key will be replaced by underscores. ```javascript transaction.mark(key) ``` -------------------------------- ### Get and Block Active Transaction Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Retrieves the current active transaction and blocks it from automatic closure. This is useful when dealing with uninstrumented asynchronous tasks. Remember to unblock the transaction when these tasks are complete. ```javascript // get the current active autoinstrumented transaction (page-load, route-change, etc.) const activeTransaction = apm.getCurrentTransaction() if (activeTransaction) { activeTransaction.block(true) } // Perform some more async tasks and unblock it activeTransaction.block(false) ``` -------------------------------- ### transaction.block Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Blocks the currently running auto-instrumented or custom transactions from getting automatically closed once the associated spans are ended. This is useful when auto-instrumented code misses important activity. ```APIDOC ## `transaction.block(flag)` ### Description Blocks the currently running auto-instrumented or custom transactions from getting automatically closed once the associated spans are ended. ### Arguments * `flag` - Boolean. Defaults to false. ### Request Example ```js // get the current active autoinstrumented transaction (page-load, route-change, etc.) const activeTransaction = apm.getCurrentTransaction() if (activeTransaction) { activeTransaction.block(true) } // Perform some more async tasks and unblock it activeTransaction.block(false) ``` ``` -------------------------------- ### apm.init([config]) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Initializes the agent with the given configuration and returns itself. It registers global listeners for errors and page load metrics. ```APIDOC ## apm.init([config]) Initializes the agent with the given configuration and returns itself. Under the hood, init does the following: * Registers a global `error` listener to track JavaScript errors on the page. * Adds a `onload` event listener to collect the page load metrics. When the agent is inactive, both `error` and `onload` listeners will not be registered on the page. Both XHR and Fetch API are patched as soon as the agent script is executed on the page and does not get changed even if the agent is inactive. The reason is to allow users to initialize the agent asynchronously on the page. ``` -------------------------------- ### Manually Release Artifacts to GitHub Source: https://github.com/elastic/apm-agent-rum-js/blob/main/RELEASE.md Execute this command in the root directory to package and create a GitHub release for '@elastic/apm-rum' using the previous annotated tag. Ensure GITHUB_TOKEN with push access is set. ```bash npm run github-release ``` -------------------------------- ### Initialize RUM Agent with Trace Context Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/distributed-tracing.md Use this when your backend service generates HTML dynamically. Inject the trace ID, parent span ID, and sampled status to ensure the page load is the root of the trace. Refer to your backend agent's API for methods to extract this information. ```javascript var apm = initApm({ ... pageLoadTraceId: , pageLoadSpanId: , pageLoadSampled: }) ``` -------------------------------- ### Run Unit Tests in Watch Mode Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Runs unit tests for a package in watch mode, automatically re-running tests when files change. Use --grep to target specific test files. ```sh npx lerna run --scope @elastic/apm-rum karma:dev -- --grep ``` -------------------------------- ### Run Linters Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Executes the linting process using ESLint and Prettier to check code style and identify potential issues. ```sh npm run lint ``` -------------------------------- ### Run Integration Tests for a Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Executes the integration tests for a specified package using Lerna. Replace @elastic/apm-rum with the target package. ```sh npx lerna run --scope @elastic/apm-rum test:integration ``` -------------------------------- ### Run Unit Tests for a Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Executes only the unit tests for a specified package using Lerna. Replace @elastic/apm-rum with the target package. ```sh npx lerna run --scope @elastic/apm-rum test:unit ``` -------------------------------- ### Configure APM RUM Agent with Bundlers Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Import and initialize the APM RUM agent within your application code when using bundlers. Configure essential parameters like `serviceName`, `serverUrl`, and `serviceVersion`. ```js import { init as initApm } from '@elastic/apm-rum' const apm = initApm({ // Set required service name (allowed characters: a-z, A-Z, 0-9, -, _, and space) serviceName: '', // Set custom APM Server URL (default: http://localhost:8200) serverUrl: 'http://localhost:8200', // Set service version (required for sourcemap feature) serviceVersion: '' }) ``` -------------------------------- ### Rollup Production Build Configuration Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Configure Rollup for an optimized production build by using the `replace` plugin. This ensures the correct build environment is set, optimizing the agent for production. ```js const replace = require('rollup-plugin-replace') plugins: [ replace({ 'process.env.NODE_ENV': JSON.stringify('production') }) ] ``` -------------------------------- ### Import withTransaction for Component Instrumentation Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Import the `withTransaction` higher-order component from the `@elastic/apm-rum-react` package to instrument individual React components. ```javascript import { withTransaction } from '@elastic/apm-rum-react' ``` -------------------------------- ### Initialize APM Agent with Custom Request Handler Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/configuration.md Initialize the APM agent with a custom `apmRequest` function to intercept and modify outgoing requests to the APM server. The function should return `true` to proceed with the request or `false` to discard it. ```javascript apm.init({ apmRequest: (requestParams) => true}) ``` ```javascript apm.init({ apmRequest({ xhr }) { xhr.setRequestHeader('custom', 'header') return true } }) ``` ```javascript apm.init({ apmRequest({ url, method, headers, payload }) { // Handle the APM request here or at some later point. fetch(url, { method, headers, body: payload }); return false } }) ``` -------------------------------- ### Ignore Transactions with Strings and Regex Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/configuration.md Configure which transaction names to ignore by providing an array of strings for exact matches or RegExp objects for pattern matching. ```javascript const options = { ignoreTransactions: [/login*/, '/app'] } ``` -------------------------------- ### Webpack Production Build Configuration Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Configure Webpack for an optimized production build by including the `EnvironmentPlugin`. This helps in removing debug messages and reducing bundle size. ```js const { EnvironmentPlugin } = require('webpack') plugins: [ new EnvironmentPlugin({ NODE_ENV: 'production' }) ] ``` -------------------------------- ### apm.setCustomContext(context) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Enriches collected errors and transactions with custom information to aid in debugging performance issues or errors. The context can be any JSON-encodable object. ```APIDOC ## apm.setCustomContext(context) Call this to enrich collected errors and transactions with any information that you think will help you debug performance issues or errors. The provided custom context is stored under `context.custom` in Elasticsearch on both errors and transactions. It’s possible to call this function multiple times within the scope of the same active transaction. For each call, the properties of the context argument are shallow merged with the context previously given. The given `context` argument must be an object and can contain any property that can be JSON encoded. ``` -------------------------------- ### Set Initial Page Load Transaction Name Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use this method to set the name of the `page-load` transaction that is sent automatically on page load event. ```javascript apm.setInitialPageLoadName(name) ``` -------------------------------- ### Instrument Lazy Loaded Routes with `withTransaction` Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md When using React.lazy for components, auto-instrumentation via ApmRoute is not possible. Use the `withTransaction` API to manually instrument code for lazy-rendered routes and capture associated spans. ```javascript import React, { Component, Suspense, lazy } from 'react' import { Route, Switch } from 'react-router-dom' import { withTransaction } from '@elastic/apm-rum-react' const Loading = () =>
Loading
const LazyRouteComponent = lazy(() => import('./lazy-component')) function Routes() { return ( ) } // lazy-component.jsx class LazyComponent extends Component {} export default withTransaction('LazyComponent', 'component')(LazyComponent) ``` -------------------------------- ### apm.setInitialPageLoadName() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Sets the name of the page-load transaction that is automatically sent on page load events. ```APIDOC ## `apm.setInitialPageLoadName()` [set-initial-page-load-name] ```js apm.setInitialPageLoadName(name) ``` Arguments: * `name` - The name of the page-load transaction (string). Use this method to set the name of the `page-load` transaction that is sent automatically on page load event. See the [custom initial page load transaction names](/reference/custom-transaction-name.md) documentation for more details. ``` -------------------------------- ### Capture Errors in Unsupported Browsers Source: https://github.com/elastic/apm-agent-rum-js/blob/main/packages/rum/test/e2e/standalone-html/opentracing.html This snippet is used for testing error capturing in unsupported browsers. It overrides the global `onerror` handler to capture any errors that occur. ```javascript test /***** * Used for testing errors on unsupported browsers *****/ window.capturedTestErrors = [] window.onerror = function(err) { window.capturedTestErrors.push(err) } ``` -------------------------------- ### Import ApmRoute for React Router v4/v5 Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Import the `ApmRoute` component from the `@elastic/apm-rum-react` package for older versions of `react-router`. ```javascript import { ApmRoute } from '@elastic/apm-rum-react' ``` -------------------------------- ### Instrument React Routes with ApmRoute (v<2.0.0) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Replace `Route` components with `ApmRoute` to monitor specific routes. This approach is for `react-router` versions 4 and 5. Ensure the `component` property is provided for instrumentation. ```javascript class App extends React.Component { render() { return (
( )} />
) } } ``` -------------------------------- ### apm.addLabels({ [name]: value }) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Sets labels on transactions and errors, which are indexed by Elasticsearch and therefore searchable. Labels can be any string, boolean, or number. ```APIDOC ## apm.addLabels({ [name]: value }) Set labels on transactions and errors. Starting with APM Server 7.6+, the labels are added to spans as well. Labels are key/value pairs that are indexed by Elasticsearch and therefore searchable (as opposed to data set via `apm.setCustomContext()`). You can set multiple labels. Arguments: * `name` - Any string. All periods (.), asterisks (*), and double quotation marks (") will be replaced by underscores (_), as those characters have special meaning in Elasticsearch * `value` - Any string, boolean, or number. All other data types will be converted to a string before being sent to the APM Server. ``` -------------------------------- ### Capture Errors on Unsupported Browsers Source: https://github.com/elastic/apm-agent-rum-js/blob/main/packages/rum/test/e2e/standalone-html/index.html This snippet is used for testing error capturing on unsupported browsers. It overrides the global `onerror` handler to push any captured errors into a global array for later assertion. ```javascript /** * Used for testing errors on unsupported browsers */ window.capturedTestErrors = [] window.onerror = function(err) { window.capturedTestErrors.push(err) } ``` -------------------------------- ### Capture and Send an Error Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use this method to manually send an error to APM Server. Additional context can be added with labels. ```javascript apm.captureError(error, options) ``` ```javascript apm.captureError(new Error('')) ``` -------------------------------- ### apm.setUserContext(context) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Enriches collected performance data and errors with information about the user. The context object can contain optional `id`, `username`, and `email` properties. ```APIDOC ## apm.setUserContext(context) Call this method to enrich collected performance data and errors with information about the user. The given `context` argument must be an object and can contain the following properties (all optional): * `id` - The users ID * `username` - The users username * `email` - The users e-mail The provided user context is stored under `context.user` in Elasticsearch on both errors and transactions. It’s possible to call this function multiple times within the scope of the same active transaction. For each call, the properties of the context argument are shallow merged with the context previously given. ``` -------------------------------- ### Instrument React Routes with ApmRoutes (v2.0.0+) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Use the `ApmRoutes` component to wrap your `Route` components from `react-router`. This automatically creates transactions for route changes. Only supports `react-router` v6. ```javascript class App extends React.Component { render() { return ( } /> } /> ) } } ``` -------------------------------- ### apm.captureError() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Manually sends an error to the APM Server, optionally including additional context via labels. ```APIDOC ## `apm.captureError()` [capture-error] ```js apm.captureError(error, options) ``` Arguments: * `error` - An instance of `Error`. * `options` - The following options are supported: * `labels` - Add additional context with labels, these labels will be added to the error along with the labels from the current transaction. Use this method to manually send an error to APM Server: ```js apm.captureError(new Error('')) ``` ``` -------------------------------- ### transaction.mark(key) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Marks a specific point in time within an active transaction. This is useful for noting significant events during the transaction's lifecycle. ```APIDOC ## `transaction.mark(key)` ### Description Marks the current point in time relative to the start of the transaction. Use this method to mark significant events that happen while the transaction is active. ### Method ```js transaction.mark(key) ``` ### Parameters #### Arguments * `key` - (string) - Any string. All periods (.), asterisks (*), and double quotation marks (") will be replaced by underscores (_), as those characters have special meaning in Elasticsearch. ``` -------------------------------- ### Instrument Individual React Components with withTransaction Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Use `withTransaction` as a function to wrap your React components, allowing you to define transaction names and types for component-level monitoring. ```javascript class AboutComponent extends React.Component { } export default withTransaction('AboutComponent', 'component')(AboutComponent) ``` -------------------------------- ### CORS Response Headers with Credentials Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/configuring-cors.md If sendCredentials is enabled, the proxy response must include these headers, including the page's origin. ```javascript Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: POST, OPTIONS Access-Control-Allow-Origin: [request-origin] Access-Control-Allow-Credentials: true ``` -------------------------------- ### Add Labels to Transaction Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Adds key/value labels to the current transaction. These labels are indexed by Elasticsearch and searchable. Avoid defining too many unique labels to prevent mapping explosions. ```javascript transaction.addLabels({ [name]: value }) ``` -------------------------------- ### span.addLabels() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/span-api.md Adds labels to a span. These labels will also be applied to any error that occurs during the span's lifetime. Special characters in label names are replaced with underscores. ```APIDOC ## span.addLabels() ### Description Adds several labels on the span. If an error happens during the span, it will also get tagged with the same labels. ### Method Signature ```js span.addLabels({ [name]: value }) ``` ### Parameters #### Labels Object - **name** (String) - Any string. All periods (.), asterisks (*), and double quotation marks (") will be replaced by underscores (_). - **value** (String, Boolean, or Number) - Any other data type will be converted to a string before being sent to the APM Server. ``` -------------------------------- ### Add Labels to Transactions and Errors Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Set searchable key/value labels on transactions, errors, and spans. Avoid defining too many unique labels to prevent mapping explosions in Elasticsearch. ```javascript apm.addLabels({ [name]: value }) ``` -------------------------------- ### transaction.addLabels Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Adds several labels to the transaction. If an error occurs during the transaction, it will also be tagged with these labels. Labels are indexed by Elasticsearch and are searchable. ```APIDOC ## `transaction.addLabels()` ### Description Add several labels on the transaction. If an error happens during the transaction, it will also get tagged with the same labels. ### Arguments * `name` - Any string. All periods (.), asterisks (*), and double quotation marks (") will be replaced by underscores (_), as those characters have special meaning in Elasticsearch * `value` - Any string, boolean, or number. All other data types will be converted to a string before being sent to the APM Server. ### Request Example ```js transaction.addLabels({ [name]: value }) ``` ``` -------------------------------- ### End Transaction with transaction.end() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Call this method to end an active transaction. If the transaction has already ended, this method has no effect. Calling end on an active transaction will also end all underlying spans and mark them as truncated. ```javascript transaction.end() ``` -------------------------------- ### apm.getCurrentTransaction() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Retrieves the current active transaction. Returns undefined if no transaction is active. ```APIDOC ## `apm.getCurrentTransaction()` [get-current-transaction] ```js apm.getCurrentTransaction() ``` Use this method to get the current active transaction. If there is no active transaction it will return `undefined`. ``` -------------------------------- ### apm.addFilter(function (payload)) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Adds a filter function to modify the APM payload before it is sent to the APM server, useful for redacting sensitive information. The filter function receives the payload and must return the modified payload. ```APIDOC ## apm.addFilter(function (payload)) A filter can be used to modify the APM payload before it is sent to the apm-server. This can be useful in for example redacting sensitive information from the payload: ```js apm.addFilter(function (payload) { if (payload.errors) { payload.errors.forEach(function (error) { error.exception.message = error.exception.message.replace('secret', '[REDACTED]') }) } if (payload.transactions) { payload.transactions.forEach(function (tr) { tr.spans.forEach(function (span) { if (span.context && span.context.http && span.context.http.url) { var url = new URL(span.context.http.url) if (url.searchParams.get('token')) { url.searchParams.set('token', 'REDACTED') } span.context.http.url = url.toString() } }) }) } // Make sure to return the payload return payload }) ``` The payload will be dropped if one of the filters return a falsy value or if after applying all filters the transactions and errors arrays are empty. ``` -------------------------------- ### span.end() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/span-api.md Ends the current span, marking the completion of the measured event. If the span has already ended, this operation has no effect. ```APIDOC ## span.end() ### Description Ends the span. If the span has already ended, nothing happens. ### Method Signature ```js span.end() ``` ``` -------------------------------- ### Add Filter to Modify APM Payload Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use a filter function to modify the APM payload before it is sent to the APM server, useful for redacting sensitive information. Ensure the payload is returned, or it will be dropped. ```javascript apm.addFilter(function (payload) { if (payload.errors) { payload.errors.forEach(function (error) { error.exception.message = error.exception.message.replace('secret', '[REDACTED]') }) } if (payload.transactions) { payload.transactions.forEach(function (tr) { tr.spans.forEach(function (span) { if (span.context && span.context.http && span.context.http.url) { var url = new URL(span.context.http.url) if (url.searchParams.get('token')) { url.searchParams.set('token', 'REDACTED') } span.context.http.url = url.toString() } }) }) } // Make sure to return the payload return payload }) ``` -------------------------------- ### transaction.end() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Ends the current transaction. If the transaction has already ended, this method has no effect. It also truncates any underlying spans. ```APIDOC ## `transaction.end()` ### Description Ends the transaction. Calling `transaction.end` on an active transaction ends all of the underlying spans and marks them as `truncated`. If the transaction has already ended, nothing happens. ### Method ```js transaction.end() ``` ``` -------------------------------- ### Block Transaction Closure Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Blocks the currently running transaction from being automatically closed when its associated spans end. Useful for transactions with uninstrumented asynchronous tasks. Call with `false` to unblock. ```javascript transaction.block(true) ```