diff --git a/docs/advanced-topics.asciidoc b/docs/advanced-topics.asciidoc deleted file mode 100644 index 273ab94b5..000000000 --- a/docs/advanced-topics.asciidoc +++ /dev/null @@ -1,85 +0,0 @@ -[[advanced-topics]] -== Advanced Topics - -* <> -* <> -* <> -* <> - -[[longtasks]] -=== How to interpret long task spans in the UI - -Long tasks is a new performance metric that can be used for measuring the -responsiveness of an application and helps developers to understand the bad user -experience. It enables detecting tasks that monopolize the UI thread for -extended periods (greater than 50 milliseconds) and block other -critical tasks from being executed as stated in the https://github.com/w3c/longtasks[official spec]. - -RUM agent automatically captures these Long tasks and include them as spans as -part of the transaction. Since long tasks currently does not have the full information on -which part of code cause slowness, it would be hard to interpret these spans. -Below you can find some tips to help with interpreting long task spans: - -* The name of the long task span, e.g.: `self`, `same-origin`, etc., implies the - origin of the task. It could be the current browsing context or inside iframes. - -* Context of the span is enriched with useful information like `attribution` - (the type of work, such as script, layout, etc), `type`, `id` and `name`, which - determines the culprit container (such as window, iframe, embed or object) - responsible for the long task. - -With the help of the transaction timeline and span timings, -one could dig deeper by marking slow application code with the -https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark[User Timing API]. -When these spans are then captured by the agent again, you could combine them -with long tasks to reveal the true source code location. - -[[typescript]] -=== Using with TypeScript - -RUM agent publishes the type definitions for the `@elastic/apm-rum` package via `types` property in `package.json`. -If you are importing the package on a TypeScript codebase, you will get automatic code completion, hover info -and method signature information on supported platforms (Visual Studio Code, etc) - -[[custom-transaction-name]] -=== Custom page load transaction names - -A common pattern to name the transactions would be to use the current URL (`window.location.href`). -However, it creates too many unique transactions (blog titles, query strings, etc.) -and would be less useful when visualizing the traces in Kibana APM UI. - -To overcome this problem, the agent groups the page load transactions based on the current URL. -Let's look at the below example - -[source,text] ----- -// Blog Posts - '/blog/:id' -https://www.elastic.co/blog/reflections-on-three-years-in-the-elastic-public-sector -https://www.elastic.co/blog/say-heya-to-the-elastic-search-awards -https://www.elastic.co/blog/and-the-winner-of-the-elasticon-2018-training-subscription-drawing-is - -// Documentation - '/guide/en/*' -https://www.elastic.co/guide/en/elastic-stack/current/index.html -https://www.elastic.co/guide/en/apm/get-started/current/index.html -https://www.elastic.co/guide/en/infrastructure/guide/current/index.html ----- - -The page load transaction names for the above URL's would be inferred automatically and categorized -as `/blog/:id` and `/guide/en/*` by the agent. The grouping logic in the agent works by recursively traversing the -URL path tree until the depth of 2 and converting them to wildcard or slugged matches based on the number of digits, special characters, -the mix of upper and lowercase characters in the path. The algorithm uses heuristics that are derived from common patterns in URL's and therefore, it might not correctly identify matches in some cases. - -If the inferred transaction names are not helpful, please set <> configuration to something -meaningful that groups transactions under the same categories (blog, guide, etc.) and avoid using the full URL at all costs. - -[source,js] ----- -import {apm} from '@elastic/apm-rum' - -apm.init({ - serviceName: "service-name", - pageLoadTransactionName: '/homepage' -}) ----- - -include::./custom-transactions.asciidoc[Custom Transactions] diff --git a/docs/agent-api.asciidoc b/docs/agent-api.asciidoc deleted file mode 100644 index 9b6ecab68..000000000 --- a/docs/agent-api.asciidoc +++ /dev/null @@ -1,298 +0,0 @@ -[[agent-api]] - -=== `Agent` API - -You can access agent API after initializing the agent: - -[source,js] ----- -var apm = require('@elastic/apm-rum').init(...) ----- - - -[float] -[[apm-init]] -==== `apm.init([config])` - -Initializes the agent with the given <> 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. - -NOTE: When the agent is inactive, both `error` and `onload` listeners will not be registered on the page - -NOTE: 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. - - - -[float] -[[apm-set-user-context]] -==== `apm.setUserContext()` - -[source,js] ----- -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. - - -[float] -[[apm-set-custom-context]] -==== `apm.setCustomContext()` - -[source,js] ----- -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. - -TIP: Before using custom context, ensure you understand the different types of -{observability-guide}/apm-api-metadata.html[metadata] that are available. - - -[float] -[[apm-add-labels]] -==== `apm.addLabels()` - -[source,js] ----- -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 <>). You can set multiple labels. - -TIP: Before using custom labels, ensure you understand the different types of -{observability-guide}/apm-api-metadata.html[metadata] that are available. - -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. - -WARNING: Avoid defining too many user-specified labels. -Defining too many unique fields in an index is a condition that can lead to a -{ref}/mapping.html#mapping-limit-settings[mapping explosion]. - -[float] -[[apm-add-filter]] -==== `apm.addFilter()` - -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: - -[source,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 -}) ----- - -NOTE: The payload will be dropped if one of the filters return a falsy value. - - -[float] -[[apm-start-transaction]] -==== `apm.startTransaction()` - -[source,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 <> method. - -* Managed transactions include information captured via our auto-instrumentations (e.g. XHR spans). - See <> 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 <> flag is set to `false` in the config. - -[float] -[[apm-start-span]] -==== `apm.startSpan()` - -[source,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 <> 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 <> flag is set to `false` in the config. - - -[float] -[[set-initial-page-load-name]] -==== `apm.setInitialPageLoadName()` - -[source,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 <> documentation for more details. - - -[float] -[[get-current-transaction]] -==== `apm.getCurrentTransaction()` - -[source,js] ----- -apm.getCurrentTransaction() ----- - -Use this method to get the current active transaction. If there is no active transaction it will return `undefined`. - -[float] -[[capture-error]] -==== `apm.captureError()` - -[source,js] ----- -apm.captureError(error) ----- - -Arguments: - -* `error` - An instance of `Error`. - -Use this method to manually send an error to APM Server: - -[source,js] ----- -apm.captureError(new Error('')) ----- - - -[float] -[[observe]] -==== `apm.observe()` - -[source,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 <>: - -[source,js] ----- -apm.observe('transaction:start', function (transaction) { - if (transaction.type === 'custom') { - transaction.name = window.document.title - transaction.addLabels({ 'custom-label': 'custom-value' }) - } -}) ----- diff --git a/docs/api.asciidoc b/docs/api.asciidoc deleted file mode 100644 index 9e2aa3dd1..000000000 --- a/docs/api.asciidoc +++ /dev/null @@ -1,21 +0,0 @@ -[[api]] -== API Reference - -The API reference documentation is divided into three parts: - -* <> - All functions and properties on the `Agent` object. -An instance of the `Agent` object is acquired by calling the `init method` the agent either via script element on the page or require the `elastic-apm-rum` module in Node.js. -The `Agent` instance is usually referred to by the variable `apm` in this documentation. - -* <> - All functions and properties on the `Transaction` object. -An instance of the `Transaction` object is acquired by calling `apm.startTransaction()`. - -* <> - All functions and properties on the `Span` object. -An instance of the `Span` object is acquired by calling `apm.startSpan()`. - -include::./agent-api.asciidoc[Agent API documentation] - -include::./transaction-api.asciidoc[Transaction API documentation] - -include::./span-api.asciidoc[Span API documentation] - diff --git a/docs/breakdown-metrics.asciidoc b/docs/breakdown-metrics.asciidoc deleted file mode 100644 index 4f27d598f..000000000 --- a/docs/breakdown-metrics.asciidoc +++ /dev/null @@ -1,38 +0,0 @@ -[[breakdown-metrics-docs]] -== Breakdown Metrics - -Breakdown metrics help you visualize where your application is spending the majority of its time -- allowing you to find the root cause of performance problems even quicker. -These metrics are calculated for each transaction based on its corresponding types. - -[float] -[[page-load-breakdown]] -=== Page load breakdown - -Page load transactions breakdown aligns closely with the processsing model of the https://www.w3.org/TR/navigation-timing/#processing-model[Navigation Timing API] -available in the browser. The different types of metrics are: - -* `DNS` - Duration of the DNS query for the current page (domainLookupEnd - domainLookupStart). - -* `TCP` - How long it took to establish the TCP connection to the server. Includes the TLS negotitaion time for HTTPS pages (connectEnd - connectStart). - -* `Request` - The time elapsed between the browser making the HTTP request and receiving the first byte of the response (responseStart - requestStart). - Also referred as TTFB (Time to First Byte). - -* `Response` - The elapsed time between the first and the last byte of the response. Referred commonly as Content Download time (responseEnd - responseStart). - -* `Processing` - Time taken to render the current page; this includes downloading necessary resources like JavaScript, Images, CSS, etc. - required by the page (domComplete - domLoading). - -* `Load` - Duration of the `load` event after the browser is done dowloading the document and resources required for rendering the page (loadEventEnd - loadEventStart). - Duration would be longer if there are multiple listeners for the load event. - -[float] -[[other-transaction-breakdown]] -=== Other transaction types - -For other transactions including SPA (Single Page Application) navigations and user created ones, the breakdown metrics are calculated based on the spans associated with the transaction. - -* If a SPA navigation transaction (route-change) spends 20% of the time downloading resources and 80% of the time waiting for the API call response, then -the transaction breakdown would indicate time spent by span type as `resource` - 20% and `http` - 80%. - -* For a transaction that has concurrent async spans, the breakdown would include the sum of time spent by each span type. diff --git a/docs/configuration.asciidoc b/docs/configuration.asciidoc deleted file mode 100644 index 93c5f2e46..000000000 --- a/docs/configuration.asciidoc +++ /dev/null @@ -1,421 +0,0 @@ -[[configuration]] -== Configuration - -While initializing the agent you can provide the following configuration options: - -[float] -[[service-name]] -=== `serviceName` - -* *Type:* String -* *Required* - -The Elastic APM service name is used to differentiate data from each of your services. -Can only contain alphanumeric characters, spaces, underscores, and dashes (must match ^[a-zA-Z0-9 _-]+$). - -[float] -[[server-url]] -=== `serverUrl` - -* *Type:* String -* *Default:* `http://localhost:8200` - -The URL used to make requests to the APM Server. - -[float] -[[server-url-prefix]] -=== `serverUrlPrefix` - -* *Type:* String -* *Default* `/intake/v${apiVersion}/rum/events` - -The server prefix URL used to make requests to the APM Server. Some ad blockers block outgoing requests -from the browser if the default server prefix URL is being used. Using a custom server prefix URL can be used to -evade the ad blocker. - -NOTE: If the default server prefix URL is overwritten, the reverse proxy that sits between the -APM Server and the rum agent must reroute traffic to `/intake/v${apiVersion}/rum/events` -so the APM Server knows what intake API to use. - -[float] -[[service-version]] -=== `serviceVersion` - -* *Type:* String - - -The version of the app. -This could be the version from your `package.json` file, -a git commit reference, -or any other string that might help you reference a specific version. -This option is used on the APM Server to find the right sourcemap file to apply to the stack trace. - - -[float] -[[active]] -=== `active` - -* *Type:* Boolean -* *Default:* `true` - -A Boolean value that specifies if the agent should be active or not. -If active, the agent will send APM transactions and track errors. -This option can be used to deactivate the agent in your staging environment. -It can also be used to sample a number of clients. Below is an example to sample 10% of the page loads: - - -[source,js] ----- -var options = { - active: Math.random() < 0.1 -} ----- - -[float] -[[instrument]] -=== `instrument` - -* *Type:* Boolean -* *Default:* `true` - -A Boolean value that specifies if the agent should automatically instrument the application to collect -performance metrics for the application. - -NOTE: Both active and instrument needs to be true for instrumentation to be running. - -[float] -[[disable-instrumentations]] -=== `disableInstrumentations` - -* *Type:* Array -* *Default:* `[]` - -A list of instrumentations which can be disabled. When disabled, no transactions or spans will be created for that type. -The valid options are: - -* `page-load` -* `history` -* `eventtarget` -* `click` -* `xmlhttprequest` -* `fetch` -* `error` - -NOTE: To disable all `http-request` transactions, add both `fetch` and `xmlhttprequest`. -to this config. - -NOTE: To disable `user-interaction` transactions, add `eventtarget` or `click` to this config. -The option `eventtarget` is deprecated and will be removed in the future releases. - -[float] -[[environment]] -=== `environment` - -* *Type:* String -* *Default:* `''` - -The environment where the service being monitored is deployed, e.g. "production", "development", "test", etc. - -Environments allow you to easily filter data on a global level in the APM app. -It's important to be consistent when naming environments across agents. -See {apm-app-ref}/filters.html#environment-selector[environment selector] in the APM app for more information. - -NOTE: This feature is fully supported in the APM app in Kibana versions >= 7.2. -You must use the query bar to filter for a specific environment in versions prior to 7.2. - -[float] -[[log-level]] -=== `logLevel` - -* *Type:* String -* *Default:* `'warn'` - - -Set the verbosity level for the agent. -This does not have any influence on the types of errors that are sent to the APM Server. This option is useful when you want to report an issue with the agent to us. - - -Possible levels are: `trace`, `debug`, `info`, `warn`, and `error`. - -[float] -[[api-version]] -=== `apiVersion` - -* *Type:* number -* *Default:* `2` - -This denotes the version of APM Server's intake API. Setting this value to any number -above `2` will compress the events (transactions and errors) payload sent to the server. - -NOTE: This feature requires APM Server >= 7.8. Setting this flag to number > 2 with older -APM server version would break the RUM payload from reaching the server. - -[float] -[[breakdown-metrics]] -=== `breakdownMetrics` - -* *Type:* Boolean -* *Default:* `false` - -Enable or disable the tracking and collection of breakdown metrics for the transaction. - -NOTE: This feature requires APM Server and Kibana >= 7.4. Setting this flag to `true` with older APM server version -would break the RUM payload from reaching the server. - -NOTE: Breakdown distribution for the transaction varies depending on the type of the transaction. -To understand the different types, see <> - -[float] -[[flush-interval]] -=== `flushInterval` - -* *Type:* Number -* *Default:* `500` - -The agent maintains a single queue to record transaction and error events when they are added. -This option sets the flush interval in *milliseconds* for the queue. - -NOTE: After each flush of the queue, the next flush isn't scheduled until an item is added to the queue. - -[float] -[[page-load-trace-id]] -=== `pageLoadTraceId` - -* *Type:* String - -This option overrides the page load transactions trace ID. - -[float] -[[page-load-parent-id]] -=== `pageLoadParentId` - -* *Type:* String - -This option allows the creation of the page load transaction as child of an existing one. By default, -the agent treats it as the root transaction. - - -[float] -[[page-load-sampled]] -=== `pageLoadSampled` - -* *Type:* Boolean - -This option overrides the page load transactions sampled property. -It is only applicable to `page-load` transactions. - - -[float] -[[page-load-span-id]] -=== `pageLoadSpanId` - -* *Type:* String - -This option overrides the ID of the span that is generated for receiving the initial document. - -[float] -[[page-load-transaction-name]] -=== `pageLoadTransactionName` - -* *Type:* String - -This option sets the name for the page load transaction. By default, transaction names for hard (page load) and soft (route change) navigations are -inferred by the agent based on the current URL. Check the <> -documentation for more details. - - -[float] -[[distributed-tracing]] -=== `distributedTracing` - -* *Type:* Boolean -* *Default:* `true` - -Distributed tracing is enabled by default. Use this option to disable it. - - -[float] -[[distributed-tracing-origins]] -=== `distributedTracingOrigins` - -* *Type:* Array -* *Default:* `[]` - -This option can be set to an array containing one or more Strings or RegExp objects and determines which origins should be monitored as part of distributed tracing. -This option is consulted when the agent is about to add the distributed tracing HTTP header (`traceparent`) to a request. -Please note that each item in the array should be a valid URL containing the origin (other parts of the url are ignored) or a RegExp object. If an item in the array is a string, an exact match will be performed. If it's a RegExp object, its test function will be called with the request origin. - -[source,js] ----- -var options = { - distributedTracingOrigins: ['https://example.com', /https?:\/\/example\.com:\d{4}/] -} ----- - -[float] -[[propagate-tracestate]] -=== `propagateTracestate` - -* *Type:* Boolean -* *Default:* `false` - -When distributed tracing is enabled, this option can be used to propagate the https://www.w3.org/TR/trace-context/#tracestate-header[tracestate] -HTTP header to the configured origins. Before enabling this flag, make sure to change your <> to avoid -Cross-Origin Resource Sharing errors. - -[float] -[[event-throttling]] -=== Event throttling - -Throttle the number of events sent to APM Server. - -[float] -[[events-limit]] -==== `eventsLimit` - -By default, the agent can only send up to `80` events every `60000` milliseconds (one minute). - -* *Type:* Number -* *Default:* `80` - -[float] -[[transaction-sample-rate]] -==== `transactionSampleRate` - -* *Type:* Number -* *Default:* `1.0` - -A number between `0.0` and `1.0` that specifies the sample rate of transactions. By default, all transactions are sampled. - - -[float] -[[central-config]] -==== `centralConfig` - -* *Type:* Boolean -* *Default:* `false` - -This option activates APM Agent Configuration via Kibana. -When set to `true`, the agent starts fetching configurations via the APM Server during the initialization phase. -These central configurations are cached in `sessionStorage`, and will not be fetched again until -the session is closed and/or `sessionStorage` is cleared. -In most cases, this means when the tab/window of the page is closed. - -NOTE: Currently, only <> can be configured via Kibana. - -NOTE: This feature requires APM Server v7.5 or later. -More information is available in {apm-app-ref}/agent-configuration.html[APM Agent configuration]. - - -[float] -[[ignore-transactions]] -==== `ignoreTransactions` - - -* *Type:* Array -* *Default:* `[]` - -An array containing a list of transaction names that should be ignored when sending the payload to the APM server. -It can be set to an array containing one or more Strings or RegExp objects. If an element in the array is a String, an exact match will be performed. -If an element in the array is a RegExp object, its test function will be called with the name of the transation. - -[source,js] ----- -const options = { - ignoreTransactions: [/login*/, '/app'] -} ----- - -NOTE: Spans that are captured as part of the ignored transactions would also be ignored. - - -[float] -[[monitor-longtasks]] -==== `monitorLongtasks` - -* *Type:* Boolean -* *Default:* `true` - -Instructs the agent to start monitoring for browser tasks that block the UI -thread and might delay other user inputs by affecting the overall page -responsiveness. Learn more about <> and how to interpret them. - - -[float] -[[apm-request]] -==== `apmRequest` - -* *Type:* Function -* *Default:* `null` - -[source,js] ----- -apm.init({ apmRequest: (requestParams) => true}) ----- - -Arguments: - -* `requestParams` - This is an object that contains the APM HTTP request details: - -** `url` - The full url of the APM server - -** `method` - Method of the HTTP request - -** `headers` - Headers of the HTTP request - -** `payload` - Body of the HTTP request - -** `xhr` - The `XMLHttpRequest` instance used by the agent to send the request - -`apmRequest` can be used to change or reject requests that are made to the -APM Server. This config can be set to a function, which is called whenever the agent -needs to make a request to the APM Server. - -The callback function is called with a single argument and is expected to return -an output synchronously. If the return value is `true` then the agent continues -with making the (potentially modified) request to the APM Server. - -If this function returns a falsy value the request is discarded with a warning in the console. - -The following example adds a header to the HTTP request: - -[source,js] ----- -apm.init({ - apmRequest({ xhr }) { - xhr.setRequestHeader('custom', 'header') - return true - } -}) ----- - -This example instructs the agent to discard the request, since it's handled by the user: - -[source,js] ----- -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 - } -}) ----- - - -[float] -[[send-credentials]] -==== `sendCredentials` - -* *Type:* Boolean -* *Default:* `false` - -This allows the agent to send cookies when making requests to the APM server. -This is useful on scenarios where the APM server is behind a reverse proxy that requires requests to be authenticated. - -NOTE: If APM Server is deployed in an origin different than the page’s origin, you will need to -<>. diff --git a/docs/custom-transactions.asciidoc b/docs/custom-transactions.asciidoc deleted file mode 100644 index 245aa305f..000000000 --- a/docs/custom-transactions.asciidoc +++ /dev/null @@ -1,57 +0,0 @@ -[[custom-transactions]] -=== Custom Transactions - -Elastic APM uses the concept of transactions and spans to collect performance data: -Spans measure a unit of operation and are grouped into transactions. - -By default, the Elastic APM JS agent creates transactions for all <> and -sends them to the apm-server. However, if the current instrumentation doesn't provide all the insights, you can create -custom transactions to fill the gaps. - -Here is an example of using custom transactions and spans: - -[source,js] ----- -const transaction = apm.startTransaction('Application start', 'custom') -const url = 'http://example.com/data.json' -const httpSpan = transaction.startSpan('GET ' + url, 'external.http') -fetch(url) - .then((resp) => { - if (!resp.ok) { - apm.captureError(new Error(`fetch failed with status ${resp.status} ${resp.statusText}`)) - } - httpSpan.end() - transaction.end() - }) ----- - -NOTE: Custom transactions are not managed by the agent, and therefore the agent does not capture spans and -other timing information shown in <>, like XHR, resource timing, etc. - -[float] -[[custom-managed-transactions]] -==== Creating a Managed transaction - -If the user is interested in associating all the other timing information and spans in the custom transactions based -on the <>, they can pass the `managed` flag to `true` while creating the -transaction and will be controlled by the agent. However, the transaction might get closed automatically once all the -associated spans are completed. If the user wants to control this behavior, they can create a blocking span that will -hold the transaction until `span.end` is called. - -[source,js] ----- -const transaction = apm.startTransaction('custom managed', 'custom', { managed: true }) -const span = transaction.startSpan('async-task', 'app', { blocking: true }) - -setTimeout(() => { - span.end() - /** - * This would also end the managed transaction once all the blocking spans are completed and - * transaction would also contain other timing information and spans similar to auto - * instrumented transactions like `page-load` and `route-change`. - */ -}, 1000) - ----- - -NOTE: Both custom and managed transactions are queued and sent together automatically at configured intervals after `transaction.end` is called. diff --git a/docs/distributed-tracing-guide.asciidoc b/docs/distributed-tracing-guide.asciidoc deleted file mode 100644 index 95ced9e2a..000000000 --- a/docs/distributed-tracing-guide.asciidoc +++ /dev/null @@ -1,129 +0,0 @@ -[[distributed-tracing-guide]] -== Distributed Tracing - -Elastic APM supports distributed tracing to enable you to analyze performance throughout your microservices -architecture by tracing all requests -- from the initial web request to your front-end service, -to queries made to your back-end services -- all in one view. - -[float] -[[enable-cors]] -=== Enable cross-origin requests - -Distributed tracing is enabled by default in the RUM agent, however, -it only includes requests made to the same origin. In order to include cross-origin -requests, you must set the `distributedTracingOrigins` configuration option. - -For example, consider an application that is served from: `https://example.com`. -By default, all of the HTTP requests made to `https://example.com` will be included in the trace. -To also include requests made to: `https://api.example.com`, -you would need to add the following configuration: - -[source,js] ----- -var apm = initApm({ - ... - distributedTracingOrigins: ['https://api.example.com'] -}) ----- - -This effectively tells the agent to add the distributed tracing HTTP header (`traceparent`) -to requests made to `https://api.example.com`. - - -[float] -[[enable-tracestate]] -==== Propagate Tracestate - -https://www.w3.org/TR/trace-context/#tracestate-header[Tracestate] can be used to provide additional vendor -specific trace information across different tracing systems and is a companion header for the `traceparent` field. - -By default, the RUM agent does not propagate the `tracestate` HTTP header to the configured origins. However, -the user can change that behaviour by enabling the <> flag which -effectively adds `tracestate` HTTP header to the configured origins. As of today, only the sampling decision is -propagated through the tracestate header. This information is then used by the APM server and the UI to -calculate the service metrics like distributions and throughput (Service Maps). - -NOTE: distributed tracing headers (traceparent and tracestate) are only appended to API calls. -To view the full trace from a backend service, see <>. -To read more about cross-origin requests and why this process is necessary, -please see the MDN page on https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS[Cross-Origin Resource Sharing]. - -[float] -[[server-configuration]] -==== Server configuration - -The RUM agent is only one of the components in a distributed trace, so -you must properly configure other components in order to use distributed tracing. -In the example above, you need to make sure `https://api.example.com` -can respond to requests that include the distributed tracing header. -Specifically, `https://api.example.com` will receive an `OPTIONS` request with the following headers: - -[source,header] ----- -Access-Control-Request-Headers: traceparent, tracestate -Access-Control-Request-Method: [request-method] -Origin: [request-origin] ----- - -And should respond to it with these headers: - -[source,header] ----- -Access-Control-Allow-Headers: traceparent, tracestate -Access-Control-Allow-Methods: [allowed-methods] -Access-Control-Allow-Origin: [request-origin] ----- - -NOTE: `Access-Control-Request-Headers` might include more headers than `traceparent` and `tracestate`. -The response should include all headers if the server wishes to let the browser send the original request. - -NOTE: To make sure all components in a distributed trace are included, -the sampling rate of backend agents might be affected by the sampling rate of the RUM agent. - - -[float] -[[backend-agent-compatibility]] -=== Backend Agent compatibility - -Starting in version 5.0, the RUM Agent supports the official W3C tracecontext `traceparent` header, -instead of the previously used `elastic-apm-traceparent` header. -Use the table below to determine which versions of our backend agents also support the official W3C -tracecontext headers. Compatible agents use the official tracecontext spec to propagate traces and can -therefor be used with the RUM Agent version >=5.0 for distributed tracing. - -NOTE: Our backend agents will support both `traceparent` and `elastic-apm-traceparent` headers -until their respective major version release. Therefore, you can safely upgrade your backend agents -before upgrading the RUM agent. - -include::./upgrading.asciidoc[tag=backend-compat-chart] - -[float] -[[dynamic-html-doc]] -=== Dynamically-generated HTML - -If your backend service generates an HTML page dynamically, -you need to inject the trace ID and parent span ID into the page when you initialize the RUM Agent. -This ensures that the web browser's page load appears as the root of the trace. As an example: - -[source,js] ----- -var apm = initApm({ - ... - pageLoadTraceId: , - pageLoadSpanId: , - pageLoadSampled: -}) ----- - -The `pageLoadSpanId` should be set to the parent ID of the backend transaction. -Most Elastic APM backend agents provide methods to extract this information. -Please refer to the relevant Agent's API for more information: - -* {apm-dotnet-ref}/public-api.html[.NET Agent: `EnsureParentId()`] -* {apm-java-ref}/public-api.html[Java Agent: `ensureParentId()`] -* Python Agent: -** {apm-py-ref}/flask-support.html[Flask integration] -** {apm-py-ref}/django-support.html[Django integration] -* {apm-ruby-ref}/api.html[Ruby Agent: `EnsureParent()`] -* {apm-go-ref}/api.html[Go Agent: `EnsureParent()`] -* {apm-node-ref}/distributed-tracing.html[Node.js Agent distributed tracing guide] diff --git a/docs/docset.yml b/docs/docset.yml new file mode 100644 index 000000000..8c3ba9bae --- /dev/null +++ b/docs/docset.yml @@ -0,0 +1,492 @@ +project: 'APM RUM agent docs' +cross_links: + - apm-agent-dotnet + - apm-agent-go + - apm-agent-java + - apm-agent-nodejs + - apm-agent-python + - apm-agent-ruby + - docs-content +toc: + - toc: reference + - toc: release-notes +subs: + ref: "https://www.elastic.co/guide/en/elasticsearch/reference/current" + ref-bare: "https://www.elastic.co/guide/en/elasticsearch/reference" + ref-8x: "https://www.elastic.co/guide/en/elasticsearch/reference/8.1" + ref-80: "https://www.elastic.co/guide/en/elasticsearch/reference/8.0" + ref-7x: "https://www.elastic.co/guide/en/elasticsearch/reference/7.17" + ref-70: "https://www.elastic.co/guide/en/elasticsearch/reference/7.0" + ref-60: "https://www.elastic.co/guide/en/elasticsearch/reference/6.0" + ref-64: "https://www.elastic.co/guide/en/elasticsearch/reference/6.4" + xpack-ref: "https://www.elastic.co/guide/en/x-pack/6.2" + logstash-ref: "https://www.elastic.co/guide/en/logstash/current" + kibana-ref: "https://www.elastic.co/guide/en/kibana/current" + kibana-ref-all: "https://www.elastic.co/guide/en/kibana" + beats-ref-root: "https://www.elastic.co/guide/en/beats" + beats-ref: "https://www.elastic.co/guide/en/beats/libbeat/current" + beats-ref-60: "https://www.elastic.co/guide/en/beats/libbeat/6.0" + beats-ref-63: "https://www.elastic.co/guide/en/beats/libbeat/6.3" + beats-devguide: "https://www.elastic.co/guide/en/beats/devguide/current" + auditbeat-ref: "https://www.elastic.co/guide/en/beats/auditbeat/current" + packetbeat-ref: "https://www.elastic.co/guide/en/beats/packetbeat/current" + metricbeat-ref: "https://www.elastic.co/guide/en/beats/metricbeat/current" + filebeat-ref: "https://www.elastic.co/guide/en/beats/filebeat/current" + functionbeat-ref: "https://www.elastic.co/guide/en/beats/functionbeat/current" + winlogbeat-ref: "https://www.elastic.co/guide/en/beats/winlogbeat/current" + heartbeat-ref: "https://www.elastic.co/guide/en/beats/heartbeat/current" + journalbeat-ref: "https://www.elastic.co/guide/en/beats/journalbeat/current" + ingest-guide: "https://www.elastic.co/guide/en/ingest/current" + fleet-guide: "https://www.elastic.co/guide/en/fleet/current" + apm-guide-ref: "https://www.elastic.co/guide/en/apm/guide/current" + apm-guide-7x: "https://www.elastic.co/guide/en/apm/guide/7.17" + apm-app-ref: "https://www.elastic.co/guide/en/kibana/current" + apm-agents-ref: "https://www.elastic.co/guide/en/apm/agent" + apm-android-ref: "https://www.elastic.co/guide/en/apm/agent/android/current" + apm-py-ref: "https://www.elastic.co/guide/en/apm/agent/python/current" + apm-py-ref-3x: "https://www.elastic.co/guide/en/apm/agent/python/3.x" + apm-node-ref-index: "https://www.elastic.co/guide/en/apm/agent/nodejs" + apm-node-ref: "https://www.elastic.co/guide/en/apm/agent/nodejs/current" + apm-node-ref-1x: "https://www.elastic.co/guide/en/apm/agent/nodejs/1.x" + apm-rum-ref: "https://www.elastic.co/guide/en/apm/agent/rum-js/current" + apm-ruby-ref: "https://www.elastic.co/guide/en/apm/agent/ruby/current" + apm-java-ref: "https://www.elastic.co/guide/en/apm/agent/java/current" + apm-go-ref: "https://www.elastic.co/guide/en/apm/agent/go/current" + apm-dotnet-ref: "https://www.elastic.co/guide/en/apm/agent/dotnet/current" + apm-php-ref: "https://www.elastic.co/guide/en/apm/agent/php/current" + apm-ios-ref: "https://www.elastic.co/guide/en/apm/agent/swift/current" + apm-lambda-ref: "https://www.elastic.co/guide/en/apm/lambda/current" + apm-attacher-ref: "https://www.elastic.co/guide/en/apm/attacher/current" + docker-logging-ref: "https://www.elastic.co/guide/en/beats/loggingplugin/current" + esf-ref: "https://www.elastic.co/guide/en/esf/current" + kinesis-firehose-ref: "https://www.elastic.co/guide/en/kinesis/{{kinesis_version}}" + estc-welcome-current: "https://www.elastic.co/guide/en/starting-with-the-elasticsearch-platform-and-its-solutions/current" + estc-welcome: "https://www.elastic.co/guide/en/starting-with-the-elasticsearch-platform-and-its-solutions/current" + estc-welcome-all: "https://www.elastic.co/guide/en/starting-with-the-elasticsearch-platform-and-its-solutions" + hadoop-ref: "https://www.elastic.co/guide/en/elasticsearch/hadoop/current" + stack-ref: "https://www.elastic.co/guide/en/elastic-stack/current" + stack-ref-67: "https://www.elastic.co/guide/en/elastic-stack/6.7" + stack-ref-68: "https://www.elastic.co/guide/en/elastic-stack/6.8" + stack-ref-70: "https://www.elastic.co/guide/en/elastic-stack/7.0" + stack-ref-80: "https://www.elastic.co/guide/en/elastic-stack/8.0" + stack-ov: "https://www.elastic.co/guide/en/elastic-stack-overview/current" + stack-gs: "https://www.elastic.co/guide/en/elastic-stack-get-started/current" + stack-gs-current: "https://www.elastic.co/guide/en/elastic-stack-get-started/current" + javaclient: "https://www.elastic.co/guide/en/elasticsearch/client/java-api/current" + java-api-client: "https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current" + java-rest: "https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current" + jsclient: "https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current" + jsclient-current: "https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current" + es-ruby-client: "https://www.elastic.co/guide/en/elasticsearch/client/ruby-api/current" + es-dotnet-client: "https://www.elastic.co/guide/en/elasticsearch/client/net-api/current" + es-php-client: "https://www.elastic.co/guide/en/elasticsearch/client/php-api/current" + es-python-client: "https://www.elastic.co/guide/en/elasticsearch/client/python-api/current" + defguide: "https://www.elastic.co/guide/en/elasticsearch/guide/2.x" + painless: "https://www.elastic.co/guide/en/elasticsearch/painless/current" + plugins: "https://www.elastic.co/guide/en/elasticsearch/plugins/current" + plugins-8x: "https://www.elastic.co/guide/en/elasticsearch/plugins/8.1" + plugins-7x: "https://www.elastic.co/guide/en/elasticsearch/plugins/7.17" + plugins-6x: "https://www.elastic.co/guide/en/elasticsearch/plugins/6.8" + glossary: "https://www.elastic.co/guide/en/elastic-stack-glossary/current" + upgrade_guide: "https://www.elastic.co/products/upgrade_guide" + blog-ref: "https://www.elastic.co/blog/" + curator-ref: "https://www.elastic.co/guide/en/elasticsearch/client/curator/current" + curator-ref-current: "https://www.elastic.co/guide/en/elasticsearch/client/curator/current" + metrics-ref: "https://www.elastic.co/guide/en/metrics/current" + metrics-guide: "https://www.elastic.co/guide/en/metrics/guide/current" + logs-ref: "https://www.elastic.co/guide/en/logs/current" + logs-guide: "https://www.elastic.co/guide/en/logs/guide/current" + uptime-guide: "https://www.elastic.co/guide/en/uptime/current" + observability-guide: "https://www.elastic.co/guide/en/observability/current" + observability-guide-all: "https://www.elastic.co/guide/en/observability" + siem-guide: "https://www.elastic.co/guide/en/siem/guide/current" + security-guide: "https://www.elastic.co/guide/en/security/current" + security-guide-all: "https://www.elastic.co/guide/en/security" + endpoint-guide: "https://www.elastic.co/guide/en/endpoint/current" + sql-odbc: "https://www.elastic.co/guide/en/elasticsearch/sql-odbc/current" + ecs-ref: "https://www.elastic.co/guide/en/ecs/current" + ecs-logging-ref: "https://www.elastic.co/guide/en/ecs-logging/overview/current" + ecs-logging-go-logrus-ref: "https://www.elastic.co/guide/en/ecs-logging/go-logrus/current" + ecs-logging-go-zap-ref: "https://www.elastic.co/guide/en/ecs-logging/go-zap/current" + ecs-logging-go-zerolog-ref: "https://www.elastic.co/guide/en/ecs-logging/go-zap/current" + ecs-logging-java-ref: "https://www.elastic.co/guide/en/ecs-logging/java/current" + ecs-logging-dotnet-ref: "https://www.elastic.co/guide/en/ecs-logging/dotnet/current" + ecs-logging-nodejs-ref: "https://www.elastic.co/guide/en/ecs-logging/nodejs/current" + ecs-logging-php-ref: "https://www.elastic.co/guide/en/ecs-logging/php/current" + ecs-logging-python-ref: "https://www.elastic.co/guide/en/ecs-logging/python/current" + ecs-logging-ruby-ref: "https://www.elastic.co/guide/en/ecs-logging/ruby/current" + ml-docs: "https://www.elastic.co/guide/en/machine-learning/current" + eland-docs: "https://www.elastic.co/guide/en/elasticsearch/client/eland/current" + eql-ref: "https://eql.readthedocs.io/en/latest/query-guide" + extendtrial: "https://www.elastic.co/trialextension" + wikipedia: "https://en.wikipedia.org/wiki" + forum: "https://discuss.elastic.co/" + xpack-forum: "https://discuss.elastic.co/c/50-x-pack" + security-forum: "https://discuss.elastic.co/c/x-pack/shield" + watcher-forum: "https://discuss.elastic.co/c/x-pack/watcher" + monitoring-forum: "https://discuss.elastic.co/c/x-pack/marvel" + graph-forum: "https://discuss.elastic.co/c/x-pack/graph" + apm-forum: "https://discuss.elastic.co/c/apm" + enterprise-search-ref: "https://www.elastic.co/guide/en/enterprise-search/current" + app-search-ref: "https://www.elastic.co/guide/en/app-search/current" + workplace-search-ref: "https://www.elastic.co/guide/en/workplace-search/current" + enterprise-search-node-ref: "https://www.elastic.co/guide/en/enterprise-search-clients/enterprise-search-node/current" + enterprise-search-php-ref: "https://www.elastic.co/guide/en/enterprise-search-clients/php/current" + enterprise-search-python-ref: "https://www.elastic.co/guide/en/enterprise-search-clients/python/current" + enterprise-search-ruby-ref: "https://www.elastic.co/guide/en/enterprise-search-clients/ruby/current" + elastic-maps-service: "https://maps.elastic.co" + integrations-docs: "https://docs.elastic.co/en/integrations" + integrations-devguide: "https://www.elastic.co/guide/en/integrations-developer/current" + time-units: "https://www.elastic.co/guide/en/elasticsearch/reference/current/api-conventions.html#time-units" + byte-units: "https://www.elastic.co/guide/en/elasticsearch/reference/current/api-conventions.html#byte-units" + apm-py-ref-v: "https://www.elastic.co/guide/en/apm/agent/python/current" + apm-node-ref-v: "https://www.elastic.co/guide/en/apm/agent/nodejs/current" + apm-rum-ref-v: "https://www.elastic.co/guide/en/apm/agent/rum-js/current" + apm-ruby-ref-v: "https://www.elastic.co/guide/en/apm/agent/ruby/current" + apm-java-ref-v: "https://www.elastic.co/guide/en/apm/agent/java/current" + apm-go-ref-v: "https://www.elastic.co/guide/en/apm/agent/go/current" + apm-ios-ref-v: "https://www.elastic.co/guide/en/apm/agent/swift/current" + apm-dotnet-ref-v: "https://www.elastic.co/guide/en/apm/agent/dotnet/current" + apm-php-ref-v: "https://www.elastic.co/guide/en/apm/agent/php/current" + ecloud: "Elastic Cloud" + esf: "Elastic Serverless Forwarder" + ess: "Elasticsearch Service" + ece: "Elastic Cloud Enterprise" + eck: "Elastic Cloud on Kubernetes" + serverless-full: "Elastic Cloud Serverless" + serverless-short: "Serverless" + es-serverless: "Elasticsearch Serverless" + es3: "Elasticsearch Serverless" + obs-serverless: "Elastic Observability Serverless" + sec-serverless: "Elastic Security Serverless" + serverless-docs: "https://docs.elastic.co/serverless" + cloud: "https://www.elastic.co/guide/en/cloud/current" + ess-utm-params: "?page=docs&placement=docs-body" + ess-baymax: "?page=docs&placement=docs-body" + ess-trial: "https://cloud.elastic.co/registration?page=docs&placement=docs-body" + ess-product: "https://www.elastic.co/cloud/elasticsearch-service?page=docs&placement=docs-body" + ess-console: "https://cloud.elastic.co?page=docs&placement=docs-body" + ess-console-name: "Elasticsearch Service Console" + ess-deployments: "https://cloud.elastic.co/deployments?page=docs&placement=docs-body" + ece-ref: "https://www.elastic.co/guide/en/cloud-enterprise/current" + eck-ref: "https://www.elastic.co/guide/en/cloud-on-k8s/current" + ess-leadin: "You can run Elasticsearch on your own hardware or use our hosted Elasticsearch Service that is available on AWS, GCP, and Azure. https://cloud.elastic.co/registration{ess-utm-params}[Try the Elasticsearch Service for free]." + ess-leadin-short: "Our hosted Elasticsearch Service is available on AWS, GCP, and Azure, and you can https://cloud.elastic.co/registration{ess-utm-params}[try it for free]." + ess-icon: "image:https://doc-icons.s3.us-east-2.amazonaws.com/logo_cloud.svg[link=\"https://cloud.elastic.co/registration{ess-utm-params}\", title=\"Supported on Elasticsearch Service\"]" + ece-icon: "image:https://doc-icons.s3.us-east-2.amazonaws.com/logo_cloud_ece.svg[link=\"https://cloud.elastic.co/registration{ess-utm-params}\", title=\"Supported on Elastic Cloud Enterprise\"]" + cloud-only: "This feature is designed for indirect use by https://cloud.elastic.co/registration{ess-utm-params}[Elasticsearch Service], https://www.elastic.co/guide/en/cloud-enterprise/{ece-version-link}[Elastic Cloud Enterprise], and https://www.elastic.co/guide/en/cloud-on-k8s/current[Elastic Cloud on Kubernetes]. Direct use is not supported." + ess-setting-change: "image:https://doc-icons.s3.us-east-2.amazonaws.com/logo_cloud.svg[link=\"{ess-trial}\", title=\"Supported on {ess}\"] indicates a change to a supported https://www.elastic.co/guide/en/cloud/current/ec-add-user-settings.html[user setting] for Elasticsearch Service." + ess-skip-section: "If you use Elasticsearch Service, skip this section. Elasticsearch Service handles these changes for you." + api-cloud: "https://www.elastic.co/docs/api/doc/cloud" + api-ece: "https://www.elastic.co/docs/api/doc/cloud-enterprise" + api-kibana-serverless: "https://www.elastic.co/docs/api/doc/serverless" + es-feature-flag: "This feature is in development and not yet available for use. This documentation is provided for informational purposes only." + es-ref-dir: "'{{elasticsearch-root}}/docs/reference'" + apm-app: "APM app" + uptime-app: "Uptime app" + synthetics-app: "Synthetics app" + logs-app: "Logs app" + metrics-app: "Metrics app" + infrastructure-app: "Infrastructure app" + siem-app: "SIEM app" + security-app: "Elastic Security app" + ml-app: "Machine Learning" + dev-tools-app: "Dev Tools" + ingest-manager-app: "Ingest Manager" + stack-manage-app: "Stack Management" + stack-monitor-app: "Stack Monitoring" + alerts-ui: "Alerts and Actions" + rules-ui: "Rules" + rac-ui: "Rules and Connectors" + connectors-ui: "Connectors" + connectors-feature: "Actions and Connectors" + stack-rules-feature: "Stack Rules" + user-experience: "User Experience" + ems: "Elastic Maps Service" + ems-init: "EMS" + hosted-ems: "Elastic Maps Server" + ipm-app: "Index Pattern Management" + ingest-pipelines: "ingest pipelines" + ingest-pipelines-app: "Ingest Pipelines" + ingest-pipelines-cap: "Ingest pipelines" + ls-pipelines: "Logstash pipelines" + ls-pipelines-app: "Logstash Pipelines" + maint-windows: "maintenance windows" + maint-windows-app: "Maintenance Windows" + maint-windows-cap: "Maintenance windows" + custom-roles-app: "Custom Roles" + data-source: "data view" + data-sources: "data views" + data-source-caps: "Data View" + data-sources-caps: "Data Views" + data-source-cap: "Data view" + data-sources-cap: "Data views" + project-settings: "Project settings" + manage-app: "Management" + index-manage-app: "Index Management" + data-views-app: "Data Views" + rules-app: "Rules" + saved-objects-app: "Saved Objects" + tags-app: "Tags" + api-keys-app: "API keys" + transforms-app: "Transforms" + connectors-app: "Connectors" + files-app: "Files" + reports-app: "Reports" + maps-app: "Maps" + alerts-app: "Alerts" + crawler: "Enterprise Search web crawler" + ents: "Enterprise Search" + app-search-crawler: "App Search web crawler" + agent: "Elastic Agent" + agents: "Elastic Agents" + fleet: "Fleet" + fleet-server: "Fleet Server" + integrations-server: "Integrations Server" + ingest-manager: "Ingest Manager" + ingest-management: "ingest management" + package-manager: "Elastic Package Manager" + integrations: "Integrations" + package-registry: "Elastic Package Registry" + artifact-registry: "Elastic Artifact Registry" + aws: "AWS" + stack: "Elastic Stack" + xpack: "X-Pack" + es: "Elasticsearch" + kib: "Kibana" + esms: "Elastic Stack Monitoring Service" + esms-init: "ESMS" + ls: "Logstash" + beats: "Beats" + auditbeat: "Auditbeat" + filebeat: "Filebeat" + heartbeat: "Heartbeat" + metricbeat: "Metricbeat" + packetbeat: "Packetbeat" + winlogbeat: "Winlogbeat" + functionbeat: "Functionbeat" + journalbeat: "Journalbeat" + es-sql: "Elasticsearch SQL" + esql: "ES|QL" + elastic-agent: "Elastic Agent" + k8s: "Kubernetes" + log-driver-long: "Elastic Logging Plugin for Docker" + security: "X-Pack security" + security-features: "security features" + operator-feature: "operator privileges feature" + es-security-features: "Elasticsearch security features" + stack-security-features: "Elastic Stack security features" + endpoint-sec: "Endpoint Security" + endpoint-cloud-sec: "Endpoint and Cloud Security" + elastic-defend: "Elastic Defend" + elastic-sec: "Elastic Security" + elastic-endpoint: "Elastic Endpoint" + swimlane: "Swimlane" + sn: "ServiceNow" + sn-itsm: "ServiceNow ITSM" + sn-itom: "ServiceNow ITOM" + sn-sir: "ServiceNow SecOps" + jira: "Jira" + ibm-r: "IBM Resilient" + webhook: "Webhook" + webhook-cm: "Webhook - Case Management" + opsgenie: "Opsgenie" + bedrock: "Amazon Bedrock" + gemini: "Google Gemini" + hive: "TheHive" + monitoring: "X-Pack monitoring" + monitor-features: "monitoring features" + stack-monitor-features: "Elastic Stack monitoring features" + watcher: "Watcher" + alert-features: "alerting features" + reporting: "X-Pack reporting" + report-features: "reporting features" + graph: "X-Pack graph" + graph-features: "graph analytics features" + searchprofiler: "Search Profiler" + xpackml: "X-Pack machine learning" + ml: "machine learning" + ml-cap: "Machine learning" + ml-init: "ML" + ml-features: "machine learning features" + stack-ml-features: "Elastic Stack machine learning features" + ccr: "cross-cluster replication" + ccr-cap: "Cross-cluster replication" + ccr-init: "CCR" + ccs: "cross-cluster search" + ccs-cap: "Cross-cluster search" + ccs-init: "CCS" + ilm: "index lifecycle management" + ilm-cap: "Index lifecycle management" + ilm-init: "ILM" + dlm: "data lifecycle management" + dlm-cap: "Data lifecycle management" + dlm-init: "DLM" + search-snap: "searchable snapshot" + search-snaps: "searchable snapshots" + search-snaps-cap: "Searchable snapshots" + slm: "snapshot lifecycle management" + slm-cap: "Snapshot lifecycle management" + slm-init: "SLM" + rollup-features: "data rollup features" + ipm: "index pattern management" + ipm-cap: "Index pattern" + rollup: "rollup" + rollup-cap: "Rollup" + rollups: "rollups" + rollups-cap: "Rollups" + rollup-job: "rollup job" + rollup-jobs: "rollup jobs" + rollup-jobs-cap: "Rollup jobs" + dfeed: "datafeed" + dfeeds: "datafeeds" + dfeed-cap: "Datafeed" + dfeeds-cap: "Datafeeds" + ml-jobs: "machine learning jobs" + ml-jobs-cap: "Machine learning jobs" + anomaly-detect: "anomaly detection" + anomaly-detect-cap: "Anomaly detection" + anomaly-job: "anomaly detection job" + anomaly-jobs: "anomaly detection jobs" + anomaly-jobs-cap: "Anomaly detection jobs" + dataframe: "data frame" + dataframes: "data frames" + dataframe-cap: "Data frame" + dataframes-cap: "Data frames" + watcher-transform: "payload transform" + watcher-transforms: "payload transforms" + watcher-transform-cap: "Payload transform" + watcher-transforms-cap: "Payload transforms" + transform: "transform" + transforms: "transforms" + transform-cap: "Transform" + transforms-cap: "Transforms" + dataframe-transform: "transform" + dataframe-transform-cap: "Transform" + dataframe-transforms: "transforms" + dataframe-transforms-cap: "Transforms" + dfanalytics-cap: "Data frame analytics" + dfanalytics: "data frame analytics" + dataframe-analytics-config: "'{dataframe} analytics config'" + dfanalytics-job: "'{dataframe} analytics job'" + dfanalytics-jobs: "'{dataframe} analytics jobs'" + dfanalytics-jobs-cap: "'{dataframe-cap} analytics jobs'" + cdataframe: "continuous data frame" + cdataframes: "continuous data frames" + cdataframe-cap: "Continuous data frame" + cdataframes-cap: "Continuous data frames" + cdataframe-transform: "continuous transform" + cdataframe-transforms: "continuous transforms" + cdataframe-transforms-cap: "Continuous transforms" + ctransform: "continuous transform" + ctransform-cap: "Continuous transform" + ctransforms: "continuous transforms" + ctransforms-cap: "Continuous transforms" + oldetection: "outlier detection" + oldetection-cap: "Outlier detection" + olscore: "outlier score" + olscores: "outlier scores" + fiscore: "feature influence score" + evaluatedf-api: "evaluate {dataframe} analytics API" + evaluatedf-api-cap: "Evaluate {dataframe} analytics API" + binarysc: "binary soft classification" + binarysc-cap: "Binary soft classification" + regression: "regression" + regression-cap: "Regression" + reganalysis: "regression analysis" + reganalysis-cap: "Regression analysis" + depvar: "dependent variable" + feature-var: "feature variable" + feature-vars: "feature variables" + feature-vars-cap: "Feature variables" + classification: "classification" + classification-cap: "Classification" + classanalysis: "classification analysis" + classanalysis-cap: "Classification analysis" + infer-cap: "Inference" + infer: "inference" + lang-ident-cap: "Language identification" + lang-ident: "language identification" + data-viz: "Data Visualizer" + file-data-viz: "File Data Visualizer" + feat-imp: "feature importance" + feat-imp-cap: "Feature importance" + nlp: "natural language processing" + nlp-cap: "Natural language processing" + apm-agent: "APM agent" + apm-go-agent: "Elastic APM Go agent" + apm-go-agents: "Elastic APM Go agents" + apm-ios-agent: "Elastic APM iOS agent" + apm-ios-agents: "Elastic APM iOS agents" + apm-java-agent: "Elastic APM Java agent" + apm-java-agents: "Elastic APM Java agents" + apm-dotnet-agent: "Elastic APM .NET agent" + apm-dotnet-agents: "Elastic APM .NET agents" + apm-node-agent: "Elastic APM Node.js agent" + apm-node-agents: "Elastic APM Node.js agents" + apm-php-agent: "Elastic APM PHP agent" + apm-php-agents: "Elastic APM PHP agents" + apm-py-agent: "Elastic APM Python agent" + apm-py-agents: "Elastic APM Python agents" + apm-ruby-agent: "Elastic APM Ruby agent" + apm-ruby-agents: "Elastic APM Ruby agents" + apm-rum-agent: "Elastic APM Real User Monitoring (RUM) JavaScript agent" + apm-rum-agents: "Elastic APM RUM JavaScript agents" + apm-lambda-ext: "Elastic APM AWS Lambda extension" + project-monitors: "project monitors" + project-monitors-cap: "Project monitors" + private-location: "Private Location" + private-locations: "Private Locations" + pwd: "YOUR_PASSWORD" + esh: "ES-Hadoop" + default-dist: "default distribution" + oss-dist: "OSS-only distribution" + observability: "Observability" + api-request-title: "Request" + api-prereq-title: "Prerequisites" + api-description-title: "Description" + api-path-parms-title: "Path parameters" + api-query-parms-title: "Query parameters" + api-request-body-title: "Request body" + api-response-codes-title: "Response codes" + api-response-body-title: "Response body" + api-example-title: "Example" + api-examples-title: "Examples" + api-definitions-title: "Properties" + multi-arg: "†footnoteref:[multi-arg,This parameter accepts multiple arguments.]" + multi-arg-ref: "†footnoteref:[multi-arg]" + yes-icon: "image:https://doc-icons.s3.us-east-2.amazonaws.com/icon-yes.png[Yes,20,15]" + no-icon: "image:https://doc-icons.s3.us-east-2.amazonaws.com/icon-no.png[No,20,15]" + es-repo: "https://github.com/elastic/elasticsearch/" + es-issue: "https://github.com/elastic/elasticsearch/issues/" + es-pull: "https://github.com/elastic/elasticsearch/pull/" + es-commit: "https://github.com/elastic/elasticsearch/commit/" + kib-repo: "https://github.com/elastic/kibana/" + kib-issue: "https://github.com/elastic/kibana/issues/" + kibana-issue: "'{kib-repo}issues/'" + kib-pull: "https://github.com/elastic/kibana/pull/" + kibana-pull: "'{kib-repo}pull/'" + kib-commit: "https://github.com/elastic/kibana/commit/" + ml-repo: "https://github.com/elastic/ml-cpp/" + ml-issue: "https://github.com/elastic/ml-cpp/issues/" + ml-pull: "https://github.com/elastic/ml-cpp/pull/" + ml-commit: "https://github.com/elastic/ml-cpp/commit/" + apm-repo: "https://github.com/elastic/apm-server/" + apm-issue: "https://github.com/elastic/apm-server/issues/" + apm-pull: "https://github.com/elastic/apm-server/pull/" + kibana-blob: "https://github.com/elastic/kibana/blob/current/" + apm-get-started-ref: "https://www.elastic.co/guide/en/apm/get-started/current" + apm-server-ref: "https://www.elastic.co/guide/en/apm/server/current" + apm-server-ref-v: "https://www.elastic.co/guide/en/apm/server/current" + apm-server-ref-m: "https://www.elastic.co/guide/en/apm/server/master" + apm-server-ref-62: "https://www.elastic.co/guide/en/apm/server/6.2" + apm-server-ref-64: "https://www.elastic.co/guide/en/apm/server/6.4" + apm-server-ref-70: "https://www.elastic.co/guide/en/apm/server/7.0" + apm-overview-ref-v: "https://www.elastic.co/guide/en/apm/get-started/current" + apm-overview-ref-70: "https://www.elastic.co/guide/en/apm/get-started/7.0" + apm-overview-ref-m: "https://www.elastic.co/guide/en/apm/get-started/master" + infra-guide: "https://www.elastic.co/guide/en/infrastructure/guide/current" + a-data-source: "a data view" + icon-bug: "pass:[]" + icon-checkInCircleFilled: "pass:[]" + icon-warningFilled: "pass:[]" diff --git a/docs/framework-integrations.asciidoc b/docs/framework-integrations.asciidoc deleted file mode 100644 index 2d9503f16..000000000 --- a/docs/framework-integrations.asciidoc +++ /dev/null @@ -1,10 +0,0 @@ -[[framework-integrations]] -== Framework-specific integrations - -* <> -* <> -* <> - -include::./react-integration.asciidoc[React Integration] -include::./angular-integration.asciidoc[Angular Integration] -include::./vue-integration.asciidoc[Vue Integration] \ No newline at end of file diff --git a/docs/index.asciidoc b/docs/index.asciidoc deleted file mode 100644 index 08b461715..000000000 --- a/docs/index.asciidoc +++ /dev/null @@ -1,37 +0,0 @@ -include::{asciidoc-dir}/../../shared/versions/stack/current.asciidoc[] -include::{asciidoc-dir}/../../shared/attributes.asciidoc[] - -ifdef::env-github[] -NOTE: For the best reading experience, -please view this documentation at https://www.elastic.co/guide/en/apm/agent/rum-js[elastic.co] -endif::[] - -= APM Real User Monitoring JavaScript Agent Reference - -include::./intro.asciidoc[] - -include::./supported-technologies.asciidoc[] - -include::./configuration.asciidoc[] - -include::./api.asciidoc[] - -include::./sourcemap.asciidoc[] - -include::./framework-integrations.asciidoc[] - -include::./distributed-tracing-guide.asciidoc[] - -include::./breakdown-metrics.asciidoc[] - -include::./opentracing.asciidoc[] - -include::./advanced-topics.asciidoc[] - -include::./performance-tuning.asciidoc[] - -include::./troubleshooting.asciidoc[] - -include::./upgrading.asciidoc[] - -include::./release-notes.asciidoc[] diff --git a/docs/intro.asciidoc b/docs/intro.asciidoc deleted file mode 100644 index eb3316026..000000000 --- a/docs/intro.asciidoc +++ /dev/null @@ -1,43 +0,0 @@ -[[intro]] -== Introduction - -The Elastic APM Real User Monitoring (RUM) JavaScript Agent provides detailed performance metrics and error tracking of your web applications. -It has built-in support for popular platforms and frameworks, and an API for custom instrumentation. - -The Agent also supports <> for all outgoing requests. -This enables you to analyze performance throughout your microservice architecture -- all in one view. - -[NOTE] -==== -The Elastic APM RUM JavaScript Agent is _not_ compatible with {serverless-docs}[{serverless-full}] -- it cannot send data to the APM endpoint for serverless projects. -==== - -[float] -[[features]] -=== Features - -The agent uses browser timing APIs such as https://w3c.github.io/navigation-timing/[Navigation Timing] -https://w3c.github.io/resource-timing/[Resource Timing], https://w3c.github.io/paint-timing/[Paint Timing], https://w3c.github.io/user-timing/[User Timing], etc., and -captures the following information: - -* <> -* Load time of Static Assets (JS, CSS, images, fonts, etc.) -* API requests (XMLHttpRequest and Fetch) -* Single page application navigations -* <> (click events that trigger network activity) -* <> (Long tasks, FCP, LCP, INP, FID, etc.) -* Page information (URLs visited and referrer) -* Network connection information -* JavaScript errors -* <> -* <> - -[float] -[[additional-components]] -=== Additional Components - -APM Agents work in conjunction with the {observability-guide}/apm.html[APM Server], {ref}/index.html[Elasticsearch], and {kibana-ref}/index.html[Kibana]. -The {observability-guide}/apm.html[APM Guide] provides details on how these components work together, -and provides a matrix outlining {observability-guide}/apm-agent-server-compatibility.html[Agent and Server compatibility]. - -include::./set-up.asciidoc[] diff --git a/docs/opentracing.asciidoc b/docs/opentracing.asciidoc deleted file mode 100644 index 564ccf4c0..000000000 --- a/docs/opentracing.asciidoc +++ /dev/null @@ -1,98 +0,0 @@ -[[opentracing]] -== OpenTracing - -Elastic APM RUM agent provides an implementation for the https://opentracing.io/[OpenTracing API]. -The `ElasticApmTracer` translates OpenTracing API calls to Elastic APM, which allows the reuse of existing instrumentation. - -The first span of a service will be converted to an Elastic APM `Transaction`, -and subsequent spans are mapped to Elastic APM `Span`. - - -[float] -[[opentracing-getting-started]] -=== Getting started - -In order to use OpenTracing API with Elastic APM, you need to first create a Tracer: - -[source,js] ----- -const { init: initApm, createTracer } = require('@elastic/apm-rum/dist/bundles/elastic-apm-opentracing.umd.js') -const elasticApm = initApm({ - // ... -}) -const elasticTracer = createTracer(elasticApm) ----- - -At this point you can either use `elasticTracer` directly, or register it as a global tracer: - -[source,js] ----- -const opentracing = require('opentracing-javascript') -opentracing.initGlobalTracer(elasticTracer); - -// ... - -const tracer = opentracing.globalTracer(); ----- - -Please refer to https://github.com/opentracing/opentracing-javascript/[opentracing-javascript] documentation for more detail -on OpenTracing API. - -NOTE: If you are loading the RUM agent using a script tag, please make sure to use our OpenTracing bundle -(`@elastic/apm-rum/dist/bundles/elastic-apm-opentracing.umd.js`) in your scripts instead, then you can create a tracer -using `window.elasticApm.createTracer()`. - - -[float] -[[opentracing-apm-tags]] -=== Elastic APM specific tags - -Elastic APM defines some tags which are not included in the OpenTracing specification, -but are relevant in the context of Elastic APM. - -- `type` - sets the type of the transaction or span, e.g. "page-load", or "ext.http". - If `type` is not specified, `custom` would be set instead. - - -The following tags are relevant only to the root spans, which are -translated to Elastic APM transactions. -These tags appear in the "User" tab on the transaction details page in the Elastic APM app. - -- `user.id` - sets the user id -- `user.email` - sets the user email -- `user.username` - sets the user name - - -[float] -[[opentracing-caveats]] -=== Caveats -Some of the OpenTracing features are not fully supported by Elastic APM RUM agent. - - -[float] -[[opentracing-propagation]] -==== Context propagation - -Currently, the only carrier formats supported are `FORMAT_HTTP_HEADERS` and `FORMAT_TEXT_MAP`. -`FORMAT_BINARY` is not supported. - -[float] -[[opentracing-references]] -==== Span References -Currently, the Elastic APM Tracer supports `REFERENCE_CHILD_OF` references. -However, only the first `REFERENCE_CHILD_OF` reference is recorded and the rest are ignored. -Other references, e.g. `follows_from`, are currently not supported. - - -[float] -[[opentracing-baggage]] -==== Baggage -The `Span.setBaggageItem` method is not supported. -Baggage items are silently dropped. - -[float] -[[opentracing-logs]] -==== Logs - -Only Error logging is supported. -Logging an Error on the OpenTracing span will create an Elastic APM Error. diff --git a/docs/performance-tuning.asciidoc b/docs/performance-tuning.asciidoc deleted file mode 100644 index d8b7e3db7..000000000 --- a/docs/performance-tuning.asciidoc +++ /dev/null @@ -1,62 +0,0 @@ -[[performance-tuning]] -== Performance Tuning - -There are different ways to optimize/tune the performance of the RUM agent. -Which options to adjust depends on whether you are optimizing for speed, memory -usage, bandwidth or storage. - - -[float] -[[performance-sampling]] -=== Sampling - -The first knob to reach for when tuning the performance of the agent is <>. -Adjusting the sampling rate controls what ratio of requests are traced. -By default, the sample rate is set at `1.0`, meaning _all_ requests are traced -and sent to the APM server. - -The sample rate will impact all four performance categories, -so simply turning down the sample rate is an easy way to improve performance. - -Here's an example of setting the sample rate to 20%: - -[source,js] ----- -import { apm } from "@elastic/apm-rum" - -apm.init({ - transactionSampleRate: 0.2 -}) ----- - -The Agent will still record the overall duration and result of unsampled -transactions, but will discard associated spans, context information or labels -before sending to the APM server. - -[float] -[[performance-breakdown-metrics]] -=== Breakdown Metrics - -Breakdown metrics help visualize where your application is spending the majority of -its time. The <> config controls whether metrics -should be calculated for each transaction based on its corresponding type. - -Setting this to `true` will increase the payload/bandwidth usage data to -the APM server. - - -[float] -[[performance-central-config]] -=== APM Agent Configuration - -Activate agent configuration via Kibana to start fetching new configuration -changes from the APM server during the agent initialization phase. - -Setting the config option <> to `true` -incurs the cost of one additional HTTP request when the agent is -initialized and generates more load to the APM server. As a result, -central configuration is disabled by default in RUM agent. - -It is recommended to disable this configuration when the instrumented -application is under heavy load. - diff --git a/docs/react-integration.asciidoc b/docs/react-integration.asciidoc deleted file mode 100644 index d54d3da4a..000000000 --- a/docs/react-integration.asciidoc +++ /dev/null @@ -1,170 +0,0 @@ -[[react-integration]] -=== React integration - -This document covers how to use Real User Monitoring JavaScript agent with React applications. -Please see our <> for configuring the Real User Monitoring agent. - -[[installing-react-integration]] -==== Installing Elastic APM React package - -Install the `@elastic/apm-rum-react` package as a dependency to your application: - -[source,bash] ----- -npm install @elastic/apm-rum-react --save ----- - -[float] -==== Instrumenting your React application - -The React integration package provides two approaches to instrumenting your application: - -[float] -===== Instrumenting application routes with @elastic/apm-rum-react >= 2.0.0 - -To instrument the application routes, you can use `ApmRoutes` component provided in the package. -`ApmRoutes` creates a transaction that has the path of the `Route` as its name and has `route-change` -as its type. - -NOTE: `ApmRoutes` only supports applications using version `6` of the -https://github.com/remix-run/react-router[`react-router`] library. - -NOTE: `RouterProvider` instrumentation is not currently supported. - -First import `ApmRoutes` from the `@elastic/apm-rum-react` package: - -[source,js] ----- -import { ApmRoutes } from '@elastic/apm-rum-react' ----- - -Then, use the `ApmRoutes` component from the `react-router` library. Every `` wrapped by `` will be monitored. - -[source,js] ----- -class App extends React.Component { - render() { - return ( - - - } /> - } /> - - - ) - } -} ----- - -[float] -===== Instrumenting application routes with @elastic/apm-rum-react < 2.0.0 - -To instrument the application routes, you can use `ApmRoute` component provided in the package. -`ApmRoute` creates a transaction that has the path of the `Route` as its name and has `route-change` -as its type. - -NOTE: `ApmRoute` only supports applications using versions `4` and `5` of the -https://github.com/remix-run/react-router[`react-router`] library. - -First import `ApmRoute` from the `@elastic/apm-rum-react` package: - -[source,js] ----- -import { ApmRoute } from '@elastic/apm-rum-react' ----- - -Then, you should replace `Route` components from the `react-router` library -with `ApmRoute`. You can use `ApmRoute` in any of the routes that you would like to monitor, - therefore, you don't have to change all of your routes: - - -[source,js] ----- -class App extends React.Component { - render() { - return ( -
- ( - - )} - /> - - -
- ) - } -} ----- - -NOTE: `ApmRoute` only instruments the route if component property is provided, in other cases, e.g. using `render` or `children` properties, -ApmRoute will only renders the route without instrumenting it, -please instrument the individual component using `withTransaction` in these cases instead. - - -[float] -===== Instrumenting individual React components - -First import `withTransaction` from the `@elastic/apm-rum-react` package: - -[source,js] ----- -import { withTransaction } from '@elastic/apm-rum-react' ----- - - -Then, you can use `withTransaction` as a function to wrap your React components: - - -[source,js] ----- -class AboutComponent extends React.Component { } -export default withTransaction('AboutComponent', 'component')(AboutComponent) ----- - - -NOTE: `withTransaction` accepts two parameters, "transaction name" and "transaction type". -If these parameters are not provided, the defaults documented in <> will be used. - - -[float] -===== Instrumenting lazy loaded routes - -When the route is rendered lazily with components using `React.lazy` or a -similar API, it is currently not possible to auto instrument the components -dependencies(JavaScript bundles, API calls, etc) via `ApmRoute` because React -suspends the underlying component until the required dependencies are available -which means our transaction is not started till React starts rendering the -underlying component. To instrument these lazy rendered routes and capture the -spans associated with the components, you'll need to manually instrument the -code with the `withTransaction` API. - -[source,js] ----- -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) ----- diff --git a/docs/redirects.asciidoc b/docs/redirects.asciidoc deleted file mode 100644 index 266c0f86e..000000000 --- a/docs/redirects.asciidoc +++ /dev/null @@ -1,9 +0,0 @@ -["appendix",role="exclude",id="redirects"] -= Deleted pages - -The following pages have moved or been deleted. - -[role="exclude",id="apm-set-tags"] -=== `apm.setTags()` - -This page has moved. Please see <> instead. diff --git a/docs/reference/advanced-topics.md b/docs/reference/advanced-topics.md new file mode 100644 index 000000000..ed4a863cc --- /dev/null +++ b/docs/reference/advanced-topics.md @@ -0,0 +1,16 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/advanced-topics.html +--- + +# Advanced topics [advanced-topics] + +* [How to interpret long task spans in the UI](/reference/longtasks.md) +* [Using with TypeScript](/reference/typescript.md) +* [Initial Page load transaction names](/reference/custom-transaction-name.md) +* [Custom Transactions](/reference/custom-transactions.md) + + + + + diff --git a/docs/reference/agent-api.md b/docs/reference/agent-api.md new file mode 100644 index 000000000..9244b1fe4 --- /dev/null +++ b/docs/reference/agent-api.md @@ -0,0 +1,260 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/agent-api.html +--- + +# Agent API [agent-api] + +You can access agent API after initializing the agent: + +```js +var apm = require('@elastic/apm-rum').init(...) +``` + + +## `apm.init([config])` [apm-init] + +Initializes the agent with the given [configuration](/reference/configuration.md) 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. + +::::{note} +When the agent is inactive, both `error` and `onload` listeners will not be registered on the page +:::: + + +::::{note} +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. +:::: + + + +## `apm.setUserContext()` [apm-set-user-context] + +```js +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. + + +## `apm.setCustomContext()` [apm-set-custom-context] + +```js +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. + +::::{tip} +Before using custom context, ensure you understand the different types of [metadata](docs-content://solutions/observability/apps/elastic-apm-events-intake-api.md#apm-api-metadata-overview) that are available. +:::: + + + +## `apm.addLabels()` [apm-add-labels] + +```js +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()`](#apm-set-custom-context)). You can set multiple labels. + +::::{tip} +Before using custom labels, ensure you understand the different types of [metadata](docs-content://solutions/observability/apps/elastic-apm-events-intake-api.md#apm-api-metadata-overview) that are available. +:::: + + +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. + +::::{warning} +Avoid defining too many user-specified labels. Defining too many unique fields in an index is a condition that can lead to a [mapping explosion](docs-content://manage-data/data-store/mapping.md#mapping-limit-settings). +:::: + + + +## `apm.addFilter()` [apm-add-filter] + +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 +}) +``` + +::::{note} +The payload will be dropped if one of the filters return a falsy value. +:::: + + + +## `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. +:::: + + + +## `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. +:::: + + + +## `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. + + +## `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.captureError()` [capture-error] + +```js +apm.captureError(error) +``` + +Arguments: + +* `error` - An instance of `Error`. + +Use this method to manually send an error to APM Server: + +```js +apm.captureError(new Error('')) +``` + + +## `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' }) + } +}) +``` + diff --git a/docs/angular-integration.asciidoc b/docs/reference/angular-integration.md similarity index 53% rename from docs/angular-integration.asciidoc rename to docs/reference/angular-integration.md index 674111a18..a292c5288 100644 --- a/docs/angular-integration.asciidoc +++ b/docs/reference/angular-integration.md @@ -1,40 +1,43 @@ -[[angular-integration]] -=== Angular integration +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/angular-integration.html +--- + +# Angular integration [angular-integration] This document covers how to use Real User Monitoring JavaScript agent with Angular applications. -[[angular-supported-versions]] -==== Supported versions +## Supported versions [angular-supported-versions] This integration supports Angular versions ≥ 12.0 -[[installing-angular-integration]] -==== Installing Elastic APM Angular package + +## Installing Elastic APM Angular package [installing-angular-integration] Install the `@elastic/apm-rum-angular` package as a dependency to your application: -[source,bash] ----- +```bash npm install @elastic/apm-rum-angular --save ----- +``` + +::::{note} +If you are using an Angular version < 12.0, use @elastic/apm-rum-angular 2.x to instrument your application. +:::: -NOTE: If you are using an Angular version < 12.0, use @elastic/apm-rum-angular 2.x to instrument your application. +::::{note} +If you are using an Angular version < 9.0, use @elastic/apm-rum-angular 1.x to instrument your application. Details are available in a [prior release](https://www.elastic.co/guide/en/apm/agent/rum-js/4.x/angular-integration.html). +:::: -NOTE: If you are using an Angular version < 9.0, use @elastic/apm-rum-angular 1.x to instrument your application. Details are available in a https://www.elastic.co/guide/en/apm/agent/rum-js/4.x/angular-integration.html[prior release]. -[float] -==== Instrumenting your Angular application -The Angular integration packages exposes the `ApmModule` and `ApmService` which uses Angular's dependency injection -pattern and will start subscribing to https://angular.io/api/router/Event[Angular Router Events] once the service is initialized. +### Instrumenting your Angular application [_instrumenting_your_angular_application] -`ApmService` must be initialized from either the application module or application component since -the RUM agent has to start capturing all the resources and API calls as soon as possible. +The Angular integration packages exposes the `ApmModule` and `ApmService` which uses Angular’s dependency injection pattern and will start subscribing to [Angular Router Events](https://angular.io/api/router/Event) once the service is initialized. +`ApmService` must be initialized from either the application module or application component since the RUM agent has to start capturing all the resources and API calls as soon as possible. -[source,js] ----- +```js import { NgModule } from '@angular/core' import { BrowserModule } from '@angular/platform-browser' import { Routes, RouterModule } from '@angular/router' @@ -65,23 +68,18 @@ export class AppModule { }) } } ----- +``` -Once the service is initialized, both page load and Single page application navigation events will be captured -as transactions with the `path` of the route as its name and `page-load` or `route-change` as type. +Once the service is initialized, both page load and Single page application navigation events will be captured as transactions with the `path` of the route as its name and `page-load` or `route-change` as type. -[float] -==== Capturing errors in Angular applications -By default, when an error is thrown inside the Angular application, the default error handler prints -the error messages to the console without rethrowing them as browser events. +### Capturing errors in Angular applications [_capturing_errors_in_angular_applications] -`ApmErrorHandler` provides a centralized error handling which captures and reports the errors -to be shown in the `APM UI` and also logs them to the browser console. +By default, when an error is thrown inside the Angular application, the default error handler prints the error messages to the console without rethrowing them as browser events. +`ApmErrorHandler` provides a centralized error handling which captures and reports the errors to be shown in the `APM UI` and also logs them to the browser console. -[source,js] ----- +```js import { ErrorHandler } from '@angular/core' import { ApmErrorHandler } from '@elastic/apm-rum-angular' @@ -94,4 +92,6 @@ import { ApmErrorHandler } from '@elastic/apm-rum-angular' ] }) class AppModule {} ----- \ No newline at end of file +``` + + diff --git a/docs/reference/api-reference.md b/docs/reference/api-reference.md new file mode 100644 index 000000000..2cf69d397 --- /dev/null +++ b/docs/reference/api-reference.md @@ -0,0 +1,16 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/api.html +--- + +# API reference [api] + +The API reference documentation is divided into three parts: + +* [The `Agent` API](/reference/agent-api.md) - All functions and properties on the `Agent` object. An instance of the `Agent` object is acquired by calling the `init method` the agent either via script element on the page or require the `elastic-apm-rum` module in Node.js. The `Agent` instance is usually referred to by the variable `apm` in this documentation. +* [The `Transaction` API](/reference/transaction-api.md) - All functions and properties on the `Transaction` object. An instance of the `Transaction` object is acquired by calling `apm.startTransaction()`. +* [The `Span` API](/reference/span-api.md) - All functions and properties on the `Span` object. An instance of the `Span` object is acquired by calling `apm.startSpan()`. + + + + diff --git a/docs/reference/breakdown-metrics.md b/docs/reference/breakdown-metrics.md new file mode 100644 index 000000000..ca97c99f4 --- /dev/null +++ b/docs/reference/breakdown-metrics.md @@ -0,0 +1,29 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/breakdown-metrics-docs.html +--- + +# Breakdown metrics [breakdown-metrics-docs] + +Breakdown metrics help you visualize where your application is spending the majority of its time — allowing you to find the root cause of performance problems even quicker. These metrics are calculated for each transaction based on its corresponding types. + + +## Page load breakdown [page-load-breakdown] + +Page load transactions breakdown aligns closely with the processsing model of the [Navigation Timing API](https://www.w3.org/TR/navigation-timing/#processing-model) available in the browser. The different types of metrics are: + +* `DNS` - Duration of the DNS query for the current page (domainLookupEnd - domainLookupStart). +* `TCP` - How long it took to establish the TCP connection to the server. Includes the TLS negotitaion time for HTTPS pages (connectEnd - connectStart). +* `Request` - The time elapsed between the browser making the HTTP request and receiving the first byte of the response (responseStart - requestStart). Also referred as TTFB (Time to First Byte). +* `Response` - The elapsed time between the first and the last byte of the response. Referred commonly as Content Download time (responseEnd - responseStart). +* `Processing` - Time taken to render the current page; this includes downloading necessary resources like JavaScript, Images, CSS, etc. required by the page (domComplete - domLoading). +* `Load` - Duration of the `load` event after the browser is done dowloading the document and resources required for rendering the page (loadEventEnd - loadEventStart). Duration would be longer if there are multiple listeners for the load event. + + +## Other transaction types [other-transaction-breakdown] + +For other transactions including SPA (Single Page Application) navigations and user created ones, the breakdown metrics are calculated based on the spans associated with the transaction. + +* If a SPA navigation transaction (route-change) spends 20% of the time downloading resources and 80% of the time waiting for the API call response, then the transaction breakdown would indicate time spent by span type as `resource` - 20% and `http` - 80%. +* For a transaction that has concurrent async spans, the breakdown would include the sum of time spent by each span type. + diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md new file mode 100644 index 000000000..740f59c2c --- /dev/null +++ b/docs/reference/configuration.md @@ -0,0 +1,365 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/configuration.html +--- + +# Configuration [configuration] + +While initializing the agent you can provide the following configuration options: + + +## `serviceName` [service-name] + +* **Type:** String +* **Required** + +The Elastic APM service name is used to differentiate data from each of your services. Can only contain alphanumeric characters, spaces, underscores, and dashes (must match `^[a-zA-Z0-9 _-]+$`). + + +## `serverUrl` [server-url] + +* **Type:** String +* **Default:** `http://localhost:8200` + +The URL used to make requests to the APM Server. + + +## `serverUrlPrefix` [server-url-prefix] + +* **Type:** String +* **Default** `/intake/v${apiVersion}/rum/events` + +The server prefix URL used to make requests to the APM Server. Some ad blockers block outgoing requests from the browser if the default server prefix URL is being used. Using a custom server prefix URL can be used to evade the ad blocker. + +::::{note} +If the default server prefix URL is overwritten, the reverse proxy that sits between the APM Server and the rum agent must reroute traffic to `/intake/v${apiVersion}/rum/events` so the APM Server knows what intake API to use. +:::: + + + +## `serviceVersion` [service-version] + +* **Type:** String + +The version of the app. This could be the version from your `package.json` file, a git commit reference, or any other string that might help you reference a specific version. This option is used on the APM Server to find the right sourcemap file to apply to the stack trace. + + +## `active` [active] + +* **Type:** Boolean +* **Default:** `true` + +A Boolean value that specifies if the agent should be active or not. If active, the agent will send APM transactions and track errors. This option can be used to deactivate the agent in your staging environment. It can also be used to sample a number of clients. Below is an example to sample 10% of the page loads: + +```js +var options = { + active: Math.random() < 0.1 +} +``` + + +## `instrument` [instrument] + +* **Type:** Boolean +* **Default:** `true` + +A Boolean value that specifies if the agent should automatically instrument the application to collect performance metrics for the application. + +::::{note} +Both active and instrument needs to be true for instrumentation to be running. +:::: + + + +## `disableInstrumentations` [disable-instrumentations] + +* **Type:** Array +* **Default:** `[]` + +A list of instrumentations which can be disabled. When disabled, no transactions or spans will be created for that type. The valid options are: + +* `page-load` +* `history` +* `eventtarget` +* `click` +* `xmlhttprequest` +* `fetch` +* `error` + +::::{note} +To disable all `http-request` transactions, add both `fetch` and `xmlhttprequest`. to this config. +:::: + + +::::{note} +To disable `user-interaction` transactions, add `eventtarget` or `click` to this config. The option `eventtarget` is deprecated and will be removed in the future releases. +:::: + + + +## `environment` [environment] + +* **Type:** String +* **Default:** `''` + +The environment where the service being monitored is deployed, e.g. "production", "development", "test", etc. + +Environments allow you to easily filter data on a global level in the APM app. It’s important to be consistent when naming environments across agents. See [environment selector](docs-content://solutions/observability/apps/filter-application-data.md#apm-filter-your-data-service-environment-filter) in the APM app for more information. + +::::{note} +This feature is fully supported in the APM app in Kibana versions >= 7.2. You must use the query bar to filter for a specific environment in versions prior to 7.2. +:::: + + + +## `logLevel` [log-level] + +* **Type:** String +* **Default:** `'warn'` + +Set the verbosity level for the agent. This does not have any influence on the types of errors that are sent to the APM Server. This option is useful when you want to report an issue with the agent to us. + +Possible levels are: `trace`, `debug`, `info`, `warn`, and `error`. + + +## `apiVersion` [api-version] + +* **Type:** number +* **Default:** `2` + +This denotes the version of APM Server’s intake API. Setting this value to any number above `2` will compress the events (transactions and errors) payload sent to the server. + +::::{note} +This feature requires APM Server >= 7.8. Setting this flag to number > 2 with older APM server version would break the RUM payload from reaching the server. +:::: + + + +## `breakdownMetrics` [breakdown-metrics] + +* **Type:** Boolean +* **Default:** `false` + +Enable or disable the tracking and collection of breakdown metrics for the transaction. + +::::{note} +This feature requires APM Server and Kibana >= 7.4. Setting this flag to `true` with older APM server version would break the RUM payload from reaching the server. +:::: + + +::::{note} +Breakdown distribution for the transaction varies depending on the type of the transaction. To understand the different types, see [*Breakdown Metrics*](/reference/breakdown-metrics.md) +:::: + + + +## `flushInterval` [flush-interval] + +* **Type:** Number +* **Default:** `500` + +The agent maintains a single queue to record transaction and error events when they are added. This option sets the flush interval in **milliseconds** for the queue. + +::::{note} +After each flush of the queue, the next flush isn’t scheduled until an item is added to the queue. +:::: + + + +## `pageLoadTraceId` [page-load-trace-id] + +* **Type:** String + +This option overrides the page load transactions trace ID. + + +## `pageLoadParentId` [page-load-parent-id] + +* **Type:** String + +This option allows the creation of the page load transaction as child of an existing one. By default, the agent treats it as the root transaction. + + +## `pageLoadSampled` [page-load-sampled] + +* **Type:** Boolean + +This option overrides the page load transactions sampled property. It is only applicable to `page-load` transactions. + + +## `pageLoadSpanId` [page-load-span-id] + +* **Type:** String + +This option overrides the ID of the span that is generated for receiving the initial document. + + +## `pageLoadTransactionName` [page-load-transaction-name] + +* **Type:** String + +This option sets the name for the page load transaction. By default, transaction names for hard (page load) and soft (route change) navigations are inferred by the agent based on the current URL. Check the [custom initial page load transaction names](/reference/custom-transaction-name.md) documentation for more details. + + +## `distributedTracing` [distributed-tracing] + +* **Type:** Boolean +* **Default:** `true` + +Distributed tracing is enabled by default. Use this option to disable it. + + +## `distributedTracingOrigins` [distributed-tracing-origins] + +* **Type:** Array +* **Default:** `[]` + +This option can be set to an array containing one or more Strings or RegExp objects and determines which origins should be monitored as part of distributed tracing. This option is consulted when the agent is about to add the distributed tracing HTTP header (`traceparent`) to a request. Please note that each item in the array should be a valid URL containing the origin (other parts of the url are ignored) or a RegExp object. If an item in the array is a string, an exact match will be performed. If it’s a RegExp object, its test function will be called with the request origin. + +```js +var options = { + distributedTracingOrigins: ['https://example.com', /https?:\/\/example\.com:\d{4}/] +} +``` + + +## `propagateTracestate` [propagate-tracestate] + +* **Type:** Boolean +* **Default:** `false` + +When distributed tracing is enabled, this option can be used to propagate the [tracestate](https://www.w3.org/TR/trace-context/#tracestate-header) HTTP header to the configured origins. Before enabling this flag, make sure to change your [server configuration](/reference/distributed-tracing.md#server-configuration) to avoid Cross-Origin Resource Sharing errors. + + +## Event throttling [event-throttling] + +Throttle the number of events sent to APM Server. + + +### `eventsLimit` [events-limit] + +By default, the agent can only send up to `80` events every `60000` milliseconds (one minute). + +* **Type:** Number +* **Default:** `80` + + +### `transactionSampleRate` [transaction-sample-rate] + +* **Type:** Number +* **Default:** `1.0` + +A number between `0.0` and `1.0` that specifies the sample rate of transactions. By default, all transactions are sampled. + + +### `centralConfig` [central-config] + +* **Type:** Boolean +* **Default:** `false` + +This option activates APM Agent Configuration via Kibana. When set to `true`, the agent starts fetching configurations via the APM Server during the initialization phase. These central configurations are cached in `sessionStorage`, and will not be fetched again until the session is closed and/or `sessionStorage` is cleared. In most cases, this means when the tab/window of the page is closed. + +::::{note} +Currently, only [transaction sample rate](#transaction-sample-rate) can be configured via Kibana. +:::: + + +::::{note} +This feature requires APM Server v7.5 or later. More information is available in [APM Agent configuration](docs-content://solutions/observability/apps/apm-agent-central-configuration.md). +:::: + + + +### `ignoreTransactions` [ignore-transactions] + +* **Type:** Array +* **Default:** `[]` + +An array containing a list of transaction names that should be ignored when sending the payload to the APM server. It can be set to an array containing one or more Strings or RegExp objects. If an element in the array is a String, an exact match will be performed. If an element in the array is a RegExp object, its test function will be called with the name of the transation. + +```js +const options = { + ignoreTransactions: [/login*/, '/app'] +} +``` + +::::{note} +Spans that are captured as part of the ignored transactions would also be ignored. +:::: + + + +### `monitorLongtasks` [monitor-longtasks] + +* **Type:** Boolean +* **Default:** `true` + +Instructs the agent to start monitoring for browser tasks that block the UI thread and might delay other user inputs by affecting the overall page responsiveness. Learn more about [long task spans](/reference/longtasks.md) and how to interpret them. + + +### `apmRequest` [apm-request] + +* **Type:** Function +* **Default:** `null` + +```js +apm.init({ apmRequest: (requestParams) => true}) +``` + +Arguments: + +* `requestParams` - This is an object that contains the APM HTTP request details: + + * `url` - The full url of the APM server + * `method` - Method of the HTTP request + * `headers` - Headers of the HTTP request + * `payload` - Body of the HTTP request + * `xhr` - The `XMLHttpRequest` instance used by the agent to send the request + + +`apmRequest` can be used to change or reject requests that are made to the APM Server. This config can be set to a function, which is called whenever the agent needs to make a request to the APM Server. + +The callback function is called with a single argument and is expected to return an output synchronously. If the return value is `true` then the agent continues with making the (potentially modified) request to the APM Server. + +If this function returns a falsy value the request is discarded with a warning in the console. + +The following example adds a header to the HTTP request: + +```js +apm.init({ + apmRequest({ xhr }) { + xhr.setRequestHeader('custom', 'header') + return true + } +}) +``` + +This example instructs the agent to discard the request, since it’s handled by the user: + +```js +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 + } +}) +``` + + +### `sendCredentials` [send-credentials] + +* **Type:** Boolean +* **Default:** `false` + +This allows the agent to send cookies when making requests to the APM server. This is useful on scenarios where the APM server is behind a reverse proxy that requires requests to be authenticated. + +::::{note} +If APM Server is deployed in an origin different than the page’s origin, you will need to [configure Cross-Origin Resource Sharing (CORS)](/reference/configuring-cors.md). +:::: + + diff --git a/docs/reference/configuring-cors.md b/docs/reference/configuring-cors.md new file mode 100644 index 000000000..07effd207 --- /dev/null +++ b/docs/reference/configuring-cors.md @@ -0,0 +1,43 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/configuring-cors.html +--- + +# Configure CORS [configuring-cors] + +If APM Server is deployed in an origin different than the page’s origin, you will need to configure Cross-Origin Resource Sharing (CORS). + +A list of permitted origins can be supplied to the [`apm-server.rum.allow_origins`](docs-content://solutions/observability/apps/configure-real-user-monitoring-rum.md#apm-rum-allow-origins) configuration option. By default, APM Server allows all origins. + + +## How CORS works [_how_cors_works] + +When the RUM agent makes its initial `POST` request, the browser will check to see if it is a cross-origin request. If it is, the browser automatically makes a preflight `OPTIONS` request to the server to ensure the original `POST` request is allowed. If this `OPTIONS` check passes, then the original `POST` request is allowed. This request will fail if RUM support is not configured in the APM Server. + +If you use a proxy, the preflight request headers may be necessary for your configuration: + +```js +Access-Control-Request-Headers: Content-Type +Access-Control-Request-Method: POST +Origin: [request-origin] +``` + +The response should include these headers: + +```js +Access-Control-Allow-Headers: Content-Type +Access-Control-Allow-Methods: POST, OPTIONS +Access-Control-Allow-Origin: [request-origin] +``` + +If you enable the [`sendCredentials`](/reference/configuration.md#send-credentials) configuration option, your proxy’s response must include the header `Access-Control-Allow-Origin` with the page’s origin as a value, and the following header: + +```js +Access-Control-Allow-Credentials: true +``` + +::::{tip} +To learn more about CORS, see the MDN page on [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). +:::: + + diff --git a/docs/reference/custom-transaction-name.md b/docs/reference/custom-transaction-name.md new file mode 100644 index 000000000..a139ed99b --- /dev/null +++ b/docs/reference/custom-transaction-name.md @@ -0,0 +1,36 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/custom-transaction-name.html +--- + +# Custom page load transaction names [custom-transaction-name] + +A common pattern to name the transactions would be to use the current URL (`window.location.href`). However, it creates too many unique transactions (blog titles, query strings, etc.) and would be less useful when visualizing the traces in Kibana APM UI. + +To overcome this problem, the agent groups the page load transactions based on the current URL. Let’s look at the below example + +```text +// Blog Posts - '/blog/:id' +https://www.elastic.co/blog/reflections-on-three-years-in-the-elastic-public-sector +https://www.elastic.co/blog/say-heya-to-the-elastic-search-awards +https://www.elastic.co/blog/and-the-winner-of-the-elasticon-2018-training-subscription-drawing-is + +// Documentation - '/guide/en/*' +https://www.elastic.co/guide/en/elastic-stack/current/index.html +https://www.elastic.co/guide/en/apm/get-started/current/index.html +https://www.elastic.co/guide/en/infrastructure/guide/current/index.html +``` + +The page load transaction names for the above URL’s would be inferred automatically and categorized as `/blog/:id` and `/guide/en/*` by the agent. The grouping logic in the agent works by recursively traversing the URL path tree until the depth of 2 and converting them to wildcard or slugged matches based on the number of digits, special characters, the mix of upper and lowercase characters in the path. The algorithm uses heuristics that are derived from common patterns in URL’s and therefore, it might not correctly identify matches in some cases. + +If the inferred transaction names are not helpful, please set [`pageLoadTransactionName`](/reference/configuration.md#page-load-transaction-name) configuration to something meaningful that groups transactions under the same categories (blog, guide, etc.) and avoid using the full URL at all costs. + +```js +import {apm} from '@elastic/apm-rum' + +apm.init({ + serviceName: "service-name", + pageLoadTransactionName: '/homepage' +}) +``` + diff --git a/docs/reference/custom-transactions.md b/docs/reference/custom-transactions.md new file mode 100644 index 000000000..93efd7337 --- /dev/null +++ b/docs/reference/custom-transactions.md @@ -0,0 +1,56 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/custom-transactions.html +--- + +# Custom Transactions [custom-transactions] + +Elastic APM uses the concept of transactions and spans to collect performance data: Spans measure a unit of operation and are grouped into transactions. + +By default, the Elastic APM JS agent creates transactions for all [supported technologies](/reference/supported-technologies.md) and sends them to the apm-server. However, if the current instrumentation doesn’t provide all the insights, you can create custom transactions to fill the gaps. + +Here is an example of using custom transactions and spans: + +```js +const transaction = apm.startTransaction('Application start', 'custom') +const url = 'http://example.com/data.json' +const httpSpan = transaction.startSpan('GET ' + url, 'external.http') +fetch(url) + .then((resp) => { + if (!resp.ok) { + apm.captureError(new Error(`fetch failed with status ${resp.status} ${resp.statusText}`)) + } + httpSpan.end() + transaction.end() + }) +``` + +::::{note} +Custom transactions are not managed by the agent, and therefore the agent does not capture spans and other timing information shown in [automatic instrumentation](/reference/supported-technologies.md), like XHR, resource timing, etc. +:::: + + + +## Creating a Managed transaction [custom-managed-transactions] + +If the user is interested in associating all the other timing information and spans in the custom transactions based on the [supported technologies](/reference/supported-technologies.md), they can pass the `managed` flag to `true` while creating the transaction and will be controlled by the agent. However, the transaction might get closed automatically once all the associated spans are completed. If the user wants to control this behavior, they can create a blocking span that will hold the transaction until `span.end` is called. + +```js +const transaction = apm.startTransaction('custom managed', 'custom', { managed: true }) +const span = transaction.startSpan('async-task', 'app', { blocking: true }) + +setTimeout(() => { + span.end() + /** + * This would also end the managed transaction once all the blocking spans are completed and + * transaction would also contain other timing information and spans similar to auto + * instrumented transactions like `page-load` and `route-change`. + */ +}, 1000) +``` + +::::{note} +Both custom and managed transactions are queued and sent together automatically at configured intervals after `transaction.end` is called. +:::: + + diff --git a/docs/reference/distributed-tracing.md b/docs/reference/distributed-tracing.md new file mode 100644 index 000000000..087ee7d8e --- /dev/null +++ b/docs/reference/distributed-tracing.md @@ -0,0 +1,111 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/distributed-tracing-guide.html +--- + +# Distributed tracing [distributed-tracing-guide] + +Elastic APM supports distributed tracing to enable you to analyze performance throughout your microservices architecture by tracing all requests — from the initial web request to your front-end service, to queries made to your back-end services — all in one view. + + +## Enable cross-origin requests [enable-cors] + +Distributed tracing is enabled by default in the RUM agent, however, it only includes requests made to the same origin. In order to include cross-origin requests, you must set the `distributedTracingOrigins` configuration option. + +For example, consider an application that is served from: `https://example.com`. By default, all of the HTTP requests made to `https://example.com` will be included in the trace. To also include requests made to: `https://api.example.com`, you would need to add the following configuration: + +```js +var apm = initApm({ + ... + distributedTracingOrigins: ['https://api.example.com'] +}) +``` + +This effectively tells the agent to add the distributed tracing HTTP header (`traceparent`) to requests made to `https://api.example.com`. + + +### Propagate Tracestate [enable-tracestate] + +[Tracestate](https://www.w3.org/TR/trace-context/#tracestate-header) can be used to provide additional vendor specific trace information across different tracing systems and is a companion header for the `traceparent` field. + +By default, the RUM agent does not propagate the `tracestate` HTTP header to the configured origins. However, the user can change that behaviour by enabling the [propagateTracestate](/reference/configuration.md#propagate-tracestate) flag which effectively adds `tracestate` HTTP header to the configured origins. As of today, only the sampling decision is propagated through the tracestate header. This information is then used by the APM server and the UI to calculate the service metrics like distributions and throughput (Service Maps). + +::::{note} +distributed tracing headers (traceparent and tracestate) are only appended to API calls. To view the full trace from a backend service, see [Dynamically-generated HTML](#dynamic-html-doc). To read more about cross-origin requests and why this process is necessary, please see the MDN page on [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). +:::: + + + +### Server configuration [server-configuration] + +The RUM agent is only one of the components in a distributed trace, so you must properly configure other components in order to use distributed tracing. In the example above, you need to make sure `https://api.example.com` can respond to requests that include the distributed tracing header. Specifically, `https://api.example.com` will receive an `OPTIONS` request with the following headers: + +```text +Access-Control-Request-Headers: traceparent, tracestate +Access-Control-Request-Method: [request-method] +Origin: [request-origin] +``` + +And should respond to it with these headers: + +```text +Access-Control-Allow-Headers: traceparent, tracestate +Access-Control-Allow-Methods: [allowed-methods] +Access-Control-Allow-Origin: [request-origin] +``` + +::::{note} +`Access-Control-Request-Headers` might include more headers than `traceparent` and `tracestate`. The response should include all headers if the server wishes to let the browser send the original request. +:::: + + +::::{note} +To make sure all components in a distributed trace are included, the sampling rate of backend agents might be affected by the sampling rate of the RUM agent. +:::: + + + +## Backend Agent compatibility [backend-agent-compatibility] + +Starting in version 5.0, the RUM Agent supports the official W3C tracecontext `traceparent` header, instead of the previously used `elastic-apm-traceparent` header. Use the table below to determine which versions of our backend agents also support the official W3C tracecontext headers. Compatible agents use the official tracecontext spec to propagate traces and can therefor be used with the RUM Agent version >=5.0 for distributed tracing. + +::::{note} +Our backend agents will support both `traceparent` and `elastic-apm-traceparent` headers until their respective major version release. Therefore, you can safely upgrade your backend agents before upgrading the RUM agent. +:::: + + +| Agent name | Agent Version | +| --- | --- | +| **Go Agent** | >= `1.6` | +| **Java Agent** | >= `1.14` | +| **.NET Agent** | >= `1.3` | +| **Node.js Agent** | >= `3.4` | +| **Python Agent** | >= `5.4` | +| **Ruby Agent** | >= `3.5` | + + +## Dynamically-generated HTML [dynamic-html-doc] + +If your backend service generates an HTML page dynamically, you need to inject the trace ID and parent span ID into the page when you initialize the RUM Agent. This ensures that the web browser’s page load appears as the root of the trace. As an example: + +```js +var apm = initApm({ + ... + pageLoadTraceId: , + pageLoadSpanId: , + pageLoadSampled: +}) +``` + +The `pageLoadSpanId` should be set to the parent ID of the backend transaction. Most Elastic APM backend agents provide methods to extract this information. Please refer to the relevant Agent’s API for more information: + +* [.NET Agent: `EnsureParentId()`](apm-agent-dotnet://reference/public-api.md) +* [Java Agent: `ensureParentId()`](apm-agent-java://reference/public-api.md) +* Python Agent: + + * [Flask integration](apm-agent-python://reference/flask-support.md) + * [Django integration](apm-agent-python://reference/django-support.md) + +* [Ruby Agent: `EnsureParent()`](apm-agent-ruby://reference/api-reference.md) +* [Go Agent: `EnsureParent()`](apm-agent-go://reference/api-documentation.md) +* [Node.js Agent distributed tracing guide](apm-agent-nodejs://reference/distributed-tracing.md) diff --git a/docs/reference/framework-specific-integrations.md b/docs/reference/framework-specific-integrations.md new file mode 100644 index 000000000..9fbf7fb97 --- /dev/null +++ b/docs/reference/framework-specific-integrations.md @@ -0,0 +1,14 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/framework-integrations.html +--- + +# Framework-specific integrations [framework-integrations] + +* [React Integration](/reference/react-integration.md) +* [Angular Integration](/reference/angular-integration.md) +* [Vue Integration](/reference/vue-integration.md) + + + + diff --git a/docs/reference/index.md b/docs/reference/index.md new file mode 100644 index 000000000..0e2f036c8 --- /dev/null +++ b/docs/reference/index.md @@ -0,0 +1,40 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/intro.html + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/index.html +--- + +# APM RUM JavaScript agent [intro] + +The Elastic APM Real User Monitoring (RUM) JavaScript Agent provides detailed performance metrics and error tracking of your web applications. It has built-in support for popular platforms and frameworks, and an API for custom instrumentation. + +The Agent also supports [distributed tracing](/reference/distributed-tracing.md) for all outgoing requests. This enables you to analyze performance throughout your microservice architecture — all in one view. + +::::{note} +The Elastic APM RUM JavaScript Agent is *not* compatible with [{{serverless-full}}](docs-content://deploy-manage/deploy/elastic-cloud/serverless.md) — it cannot send data to the APM endpoint for serverless projects. + +:::: + + + +## Features [features] + +The agent uses browser timing APIs such as [Navigation Timing](https://w3c.github.io/navigation-timing/) [Resource Timing](https://w3c.github.io/resource-timing/), [Paint Timing](https://w3c.github.io/paint-timing/), [User Timing](https://w3c.github.io/user-timing/), etc., and captures the following information: + +* [Page load metrics](/reference/supported-technologies.md#page-load-metrics) +* Load time of Static Assets (JS, CSS, images, fonts, etc.) +* API requests (XMLHttpRequest and Fetch) +* Single page application navigations +* [User interactions](/reference/supported-technologies.md#user-interactions) (click events that trigger network activity) +* [User-centric metrics](/reference/supported-technologies.md#user-centric-metrics) (Long tasks, FCP, LCP, INP, FID, etc.) +* Page information (URLs visited and referrer) +* Network connection information +* JavaScript errors +* [Distributed tracing](/reference/distributed-tracing.md) +* [Breakdown metrics](/reference/breakdown-metrics.md) + + +## Additional Components [additional-components] + +APM Agents work in conjunction with the [APM Server](docs-content://reference/ingestion-tools/observability/apm.md), [Elasticsearch](docs-content://get-started/index.md), and [Kibana](docs-content://get-started/the-stack.md). The [APM Guide](docs-content://reference/ingestion-tools/observability/apm.md) provides details on how these components work together, and provides a matrix outlining [Agent and Server compatibility](docs-content://solutions/observability/apps/apm-agent-compatibility.md). + diff --git a/docs/reference/install-agent.md b/docs/reference/install-agent.md new file mode 100644 index 000000000..582c62cc2 --- /dev/null +++ b/docs/reference/install-agent.md @@ -0,0 +1,128 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/install-the-agent.html +--- + +# Install the Agent [install-the-agent] + +There are multiple ways to add the APM RUM Agent to your web page: + +* [Using Script Tags](#using-script-tags): Add a ` + +``` + + +## Asynchronous / Non-Blocking Pattern [_asynchronous_non_blocking_pattern] + +Loading the script asynchronously ensures the agent script will not block other resources on the page, however, it will still block browsers `onload` event. + +```html + +``` + +Even though this is the recommended pattern, there is a caveat to be aware of. Because the downloading and initializing of the agent happens asynchronously, distributed tracing will not work for requests that occur before the agent is initialized. + +::::{note} +Please download the latest version of RUM agent from [GitHub](https://github.com/elastic/apm-agent-rum-js/releases/latest) or [UNPKG](https://unpkg.com/@elastic/apm-rum/dist/bundles/elastic-apm-rum.umd.min.js) and host the file in your Server/CDN before deploying to production. Remember to use a proper versioning scheme and set a far future `max-age` and `immutable` in the [cache-control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) header, as the file never changes. +:::: + + +The debug messages are removed by default from the minified bundles. It is strongly recommended to use the unminified version for debugging purposes. + + +## Using Bundlers [using-bundlers] + +Install the Real User Monitoring APM agent as a dependency to your application: + +```bash +npm install @elastic/apm-rum --save +``` + +Configure the agent: + +```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: '' +}) +``` + + +### Production Build [production-build] + +By default, RUM agent logs all the debug messages to the browser console. These logs are very useful in development. However, they make the RUM agent bundle size larger so you should make sure to use the optimized production version when deploying your application. + +You can find instructions for building optimized code below for different bundlers. + + +### Webpack [_webpack] + +For optimized webpack production build, include the Environment/Define plugin in the webpack configuration. + +```js +const { EnvironmentPlugin } = require('webpack') + +plugins: [ + new EnvironmentPlugin({ + NODE_ENV: 'production' + }) +] +``` + +You can learn more about this in [Webpack documentation](https://webpack.js.org/plugins/environment-plugin). + + +### Rollup [_rollup] + +For optimized rollup production build, include the replace plugin which ensures the right build environment is used. + +```js +const replace = require('rollup-plugin-replace') + +plugins: [ + replace({ + 'process.env.NODE_ENV': JSON.stringify('production') + }) +] +``` + +::::{note} +Currently the optimized (minified + gzipped) agent bundle size is about 16KiB. +:::: + + + diff --git a/docs/reference/longtasks.md b/docs/reference/longtasks.md new file mode 100644 index 000000000..cccdf9949 --- /dev/null +++ b/docs/reference/longtasks.md @@ -0,0 +1,16 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/longtasks.html +--- + +# How to interpret long task spans in the UI [longtasks] + +Long tasks is a new performance metric that can be used for measuring the responsiveness of an application and helps developers to understand the bad user experience. It enables detecting tasks that monopolize the UI thread for extended periods (greater than 50 milliseconds) and block other critical tasks from being executed as stated in the [official spec](https://github.com/w3c/longtasks). + +RUM agent automatically captures these Long tasks and include them as spans as part of the transaction. Since long tasks currently does not have the full information on which part of code cause slowness, it would be hard to interpret these spans. Below you can find some tips to help with interpreting long task spans: + +* The name of the long task span, e.g.: `self`, `same-origin`, etc., implies the origin of the task. It could be the current browsing context or inside iframes. +* Context of the span is enriched with useful information like `attribution` (the type of work, such as script, layout, etc), `type`, `id` and `name`, which determines the culprit container (such as window, iframe, embed or object) responsible for the long task. + +With the help of the transaction timeline and span timings, one could dig deeper by marking slow application code with the [User Timing API](https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark). When these spans are then captured by the agent again, you could combine them with long tasks to reveal the true source code location. + diff --git a/docs/reference/opentracing.md b/docs/reference/opentracing.md new file mode 100644 index 000000000..a1cd93a14 --- /dev/null +++ b/docs/reference/opentracing.md @@ -0,0 +1,80 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/opentracing.html +--- + +# OpenTracing [opentracing] + +Elastic APM RUM agent provides an implementation for the [OpenTracing API](https://opentracing.io/). The `ElasticApmTracer` translates OpenTracing API calls to Elastic APM, which allows the reuse of existing instrumentation. + +The first span of a service will be converted to an Elastic APM `Transaction`, and subsequent spans are mapped to Elastic APM `Span`. + + +## Getting started [opentracing-getting-started] + +In order to use OpenTracing API with Elastic APM, you need to first create a Tracer: + +```js +const { init: initApm, createTracer } = require('@elastic/apm-rum/dist/bundles/elastic-apm-opentracing.umd.js') +const elasticApm = initApm({ + // ... +}) +const elasticTracer = createTracer(elasticApm) +``` + +At this point you can either use `elasticTracer` directly, or register it as a global tracer: + +```js +const opentracing = require('opentracing-javascript') +opentracing.initGlobalTracer(elasticTracer); + +// ... + +const tracer = opentracing.globalTracer(); +``` + +Please refer to [opentracing-javascript](https://github.com/opentracing/opentracing-javascript/) documentation for more detail on OpenTracing API. + +::::{note} +If you are loading the RUM agent using a script tag, please make sure to use our OpenTracing bundle (`@elastic/apm-rum/dist/bundles/elastic-apm-opentracing.umd.js`) in your scripts instead, then you can create a tracer using `window.elasticApm.createTracer()`. +:::: + + + +## Elastic APM specific tags [opentracing-apm-tags] + +Elastic APM defines some tags which are not included in the OpenTracing specification, but are relevant in the context of Elastic APM. + +* `type` - sets the type of the transaction or span, e.g. "page-load", or "ext.http". If `type` is not specified, `custom` would be set instead. + +The following tags are relevant only to the root spans, which are translated to Elastic APM transactions. These tags appear in the "User" tab on the transaction details page in the Elastic APM app. + +* `user.id` - sets the user id +* `user.email` - sets the user email +* `user.username` - sets the user name + + +## Caveats [opentracing-caveats] + +Some of the OpenTracing features are not fully supported by Elastic APM RUM agent. + + +### Context propagation [opentracing-propagation] + +Currently, the only carrier formats supported are `FORMAT_HTTP_HEADERS` and `FORMAT_TEXT_MAP`. `FORMAT_BINARY` is not supported. + + +### Span References [opentracing-references] + +Currently, the Elastic APM Tracer supports `REFERENCE_CHILD_OF` references. However, only the first `REFERENCE_CHILD_OF` reference is recorded and the rest are ignored. Other references, e.g. `follows_from`, are currently not supported. + + +### Baggage [opentracing-baggage] + +The `Span.setBaggageItem` method is not supported. Baggage items are silently dropped. + + +### Logs [opentracing-logs] + +Only Error logging is supported. Logging an Error on the OpenTracing span will create an Elastic APM Error. + diff --git a/docs/reference/performance-tuning.md b/docs/reference/performance-tuning.md new file mode 100644 index 000000000..cadd94451 --- /dev/null +++ b/docs/reference/performance-tuning.md @@ -0,0 +1,44 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/performance-tuning.html +--- + +# Performance tuning [performance-tuning] + +There are different ways to optimize/tune the performance of the RUM agent. Which options to adjust depends on whether you are optimizing for speed, memory usage, bandwidth or storage. + + +## Sampling [performance-sampling] + +The first knob to reach for when tuning the performance of the agent is [`transactionSampleRate`](/reference/configuration.md#transaction-sample-rate). Adjusting the sampling rate controls what ratio of requests are traced. By default, the sample rate is set at `1.0`, meaning *all* requests are traced and sent to the APM server. + +The sample rate will impact all four performance categories, so simply turning down the sample rate is an easy way to improve performance. + +Here’s an example of setting the sample rate to 20%: + +```js +import { apm } from "@elastic/apm-rum" + +apm.init({ + transactionSampleRate: 0.2 +}) +``` + +The Agent will still record the overall duration and result of unsampled transactions, but will discard associated spans, context information or labels before sending to the APM server. + + +## Breakdown Metrics [performance-breakdown-metrics] + +Breakdown metrics help visualize where your application is spending the majority of its time. The [`breakdownMetrics`](/reference/configuration.md#breakdown-metrics) config controls whether metrics should be calculated for each transaction based on its corresponding type. + +Setting this to `true` will increase the payload/bandwidth usage data to the APM server. + + +## APM Agent Configuration [performance-central-config] + +Activate agent configuration via Kibana to start fetching new configuration changes from the APM server during the agent initialization phase. + +Setting the config option [`centralConfig`](/reference/configuration.md#central-config) to `true` incurs the cost of one additional HTTP request when the agent is initialized and generates more load to the APM server. As a result, central configuration is disabled by default in RUM agent. + +It is recommended to disable this configuration when the instrumented application is under heavy load. + diff --git a/docs/reference/react-integration.md b/docs/reference/react-integration.md new file mode 100644 index 000000000..fcc4781e0 --- /dev/null +++ b/docs/reference/react-integration.md @@ -0,0 +1,157 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/react-integration.html +--- + +# React integration [react-integration] + +This document covers how to use Real User Monitoring JavaScript agent with React applications. Please see our [Getting started guide](/reference/set-up-apm-real-user-monitoring-javascript-agent.md) for configuring the Real User Monitoring agent. + +## Installing Elastic APM React package [installing-react-integration] + +Install the `@elastic/apm-rum-react` package as a dependency to your application: + +```bash +npm install @elastic/apm-rum-react --save +``` + + +### Instrumenting your React application [_instrumenting_your_react_application] + +The React integration package provides two approaches to instrumenting your application: + + +#### Instrumenting application routes with @elastic/apm-rum-react >= 2.0.0 [_instrumenting_application_routes_with_elasticapm_rum_react_2_0_0] + +To instrument the application routes, you can use `ApmRoutes` component provided in the package. `ApmRoutes` creates a transaction that has the path of the `Route` as its name and has `route-change` as its type. + +::::{note} +`ApmRoutes` only supports applications using version `6` of the [`react-router`](https://github.com/remix-run/react-router) library. +:::: + + +::::{note} +`RouterProvider` instrumentation is not currently supported. +:::: + + +First import `ApmRoutes` from the `@elastic/apm-rum-react` package: + +```js +import { ApmRoutes } from '@elastic/apm-rum-react' +``` + +Then, use the `ApmRoutes` component from the `react-router` library. Every `` wrapped by `` will be monitored. + +```js +class App extends React.Component { + render() { + return ( + + + } /> + } /> + + + ) + } +} +``` + + +#### Instrumenting application routes with @elastic/apm-rum-react < 2.0.0 [_instrumenting_application_routes_with_elasticapm_rum_react_2_0_0_2] + +To instrument the application routes, you can use `ApmRoute` component provided in the package. `ApmRoute` creates a transaction that has the path of the `Route` as its name and has `route-change` as its type. + +::::{note} +`ApmRoute` only supports applications using versions `4` and `5` of the [`react-router`](https://github.com/remix-run/react-router) library. +:::: + + +First import `ApmRoute` from the `@elastic/apm-rum-react` package: + +```js +import { ApmRoute } from '@elastic/apm-rum-react' +``` + +Then, you should replace `Route` components from the `react-router` library with `ApmRoute`. You can use `ApmRoute` in any of the routes that you would like to monitor, therefore, you don’t have to change all of your routes: + +```js +class App extends React.Component { + render() { + return ( +
+ ( + + )} + /> + + +
+ ) + } +} +``` + +::::{note} +`ApmRoute` only instruments the route if component property is provided, in other cases, e.g. using `render` or `children` properties, ApmRoute will only renders the route without instrumenting it, please instrument the individual component using `withTransaction` in these cases instead. +:::: + + + +#### Instrumenting individual React components [_instrumenting_individual_react_components] + +First import `withTransaction` from the `@elastic/apm-rum-react` package: + +```js +import { withTransaction } from '@elastic/apm-rum-react' +``` + +Then, you can use `withTransaction` as a function to wrap your React components: + +```js +class AboutComponent extends React.Component { } +export default withTransaction('AboutComponent', 'component')(AboutComponent) +``` + +::::{note} +`withTransaction` accepts two parameters, "transaction name" and "transaction type". If these parameters are not provided, the defaults documented in [Transaction API](/reference/transaction-api.md) will be used. +:::: + + + +#### Instrumenting lazy loaded routes [_instrumenting_lazy_loaded_routes] + +When the route is rendered lazily with components using `React.lazy` or a similar API, it is currently not possible to auto instrument the components dependencies(JavaScript bundles, API calls, etc) via `ApmRoute` because React suspends the underlying component until the required dependencies are available which means our transaction is not started till React starts rendering the underlying component. To instrument these lazy rendered routes and capture the spans associated with the components, you’ll need to manually instrument the code with the `withTransaction` API. + +```js +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) +``` + + diff --git a/docs/reference/set-up-apm-real-user-monitoring-javascript-agent.md b/docs/reference/set-up-apm-real-user-monitoring-javascript-agent.md new file mode 100644 index 000000000..f1e73b128 --- /dev/null +++ b/docs/reference/set-up-apm-real-user-monitoring-javascript-agent.md @@ -0,0 +1,16 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/getting-started.html +--- + +# Set up the APM Real User Monitoring JavaScript Agent [getting-started] + +To start reporting your web page performance to Elastic APM, you must first [enable the RUM endpoint](docs-content://solutions/observability/apps/configure-real-user-monitoring-rum.md) in your `apm-server` configuration. + +Once the APM Server endpoint has been configured, you can: + +* [Install the Agent](/reference/install-agent.md) +* [Configure CORS](/reference/configuring-cors.md) + + + diff --git a/docs/reference/source-maps.md b/docs/reference/source-maps.md new file mode 100644 index 000000000..ddbcb455d --- /dev/null +++ b/docs/reference/source-maps.md @@ -0,0 +1,23 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/sourcemap.html +--- + +# Source maps [sourcemap] + +Minifying JavaScript bundles is a common practice in production as it can improve the load time and network latency of your application. However, minified code by itself can be hard to debug. For this reason, Elastic APM supports source maps. A source map is a file that maps minified files back to the original source code, allowing you to maintain the speed advantage of minified code, without losing the ability to quickly and easily debug your applications. + +There are three steps required to enable, upload, and apply a source map to error stack traces. An overview is listed below, and a complete walk-through is available in the [generate and upload a source map](docs-content://solutions/observability/apps/create-upload-source-maps-rum.md) guide. + +1. Set the [`serviceVersion`](/reference/configuration.md#service-version) when initializing the RUM Agent. +2. [Generate a source map](docs-content://solutions/observability/apps/create-upload-source-maps-rum.md#apm-source-map-rum-generate) for your application with the `serviceVersion` from step one. +3. [Enable and upload the source map file](docs-content://solutions/observability/apps/create-upload-source-maps-rum.md#apm-source-map-rum-upload) to APM Server. + +$$$secret-token$$$ +You can also configure a [secret token](docs-content://solutions/observability/apps/secret-token.md) or [API key](docs-content://solutions/observability/apps/api-keys.md) to restrict the uploading of sourcemaps. + +::::{tip} +Don’t forget, you must enable [RUM support](docs-content://solutions/observability/apps/configure-real-user-monitoring-rum.md) in the APM Server for this endpoint to work. +:::: + + diff --git a/docs/reference/span-api.md b/docs/reference/span-api.md new file mode 100644 index 000000000..b58bde8f0 --- /dev/null +++ b/docs/reference/span-api.md @@ -0,0 +1,54 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/span-api.html +--- + +# Span API [span-api] + +A span measures the duration of a single event. When a span is created it will measure the time until [`span.end()`](#span-end) is called. + +To get a `Span` object, you need to call [`apm.startSpan()`](/reference/agent-api.md#apm-start-span). + + +## `span.name` [span-name] + +* **Type:** String +* **Default:** `Unknown` + +The name of the span. This can also be set via [`apm.startSpan()`](/reference/agent-api.md#apm-start-span). + + +## `span.type` [span-type] + +* **Type:** String +* **Default:** `custom` + +The type of span. This can also be set via [`apm.startSpan()`](/reference/agent-api.md#apm-start-span). + +The type is a hierarchical string used to group similar spans together. For instance, all outgoing AJAX requests are given the type `external.http`. + +In the above example, `external` is considered the type prefix. Though there are no naming restrictions for this prefix, the following are standardized across all Elastic APM agents: `app`, `db`, `cache`, `template`, and `external`. + + +## `span.addLabels()` [span-add-labels] + +```js +span.addLabels({ [name]: value }) +``` + +Add several labels on the span. If an error happens during the span, 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. + + +## `span.end()` [span-end] + +```js +span.end() +``` + +Ends the span. If the span has already ended, nothing happens. + diff --git a/docs/reference/supported-technologies.md b/docs/reference/supported-technologies.md new file mode 100644 index 000000000..bdb2c20f0 --- /dev/null +++ b/docs/reference/supported-technologies.md @@ -0,0 +1,109 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/supported-technologies.html +--- + +# Supported technologies [supported-technologies] + + +## Page load metrics [page-load-metrics] + +The RUM agent tries to capture the overall user experience on how the page is loaded/rendered as part of the page load Transaction. It includes all of the dependent resources, like JavaScript, stylesheets, images, etc., which are included as part of the page. In addition to capturing the resource timing information as Spans, the transaction also includes navigation spans—marks that are associated with the rest of the captured information to make the waterfall more appealing. + +`Domain lookup` +: Duration of the DNS query for the current page: `domainLookupEnd` - `domainLookupStart`. + +`Making a connection to the server` +: Duration of the TCP connection to the server, including the TLS negotiation time for HTTPS pages: `connectEnd` - `connectStart`. + +`Requesting and receiving the document` +: Overall response time of the server including the last byte: `responseEnd` - `requestStart`. + +`Parsing the document, executing sync. scripts` +: HTML document parsing time, including synchronous Stylesheets and Script: `tagsdomInteractive` - `domLoading`. + +`Fire "DOMContentLoaded" event` +: Triggered when the browser completes parsing the document. Helpful when there are multiple listeners, or logic is executed: `domContentLoadedEventEnd` - `domContentLoadedEventStart`. + +`Fire "load" event` +: Trigged when the browser finishes loading its document and dependent resources: `loadEventEnd` - `loadEventStart`. + +`Time to first byte (TTFB)` +: Duration from the browser making an HTTP request for the initial document to the first byte of the page being received. TTFB is available from the Navigation Timing API as the `reponseStart` timestamp, and captured as transaction mark `transaction.marks.agent.timeToFirstByte` in the ElasticSearch document. + +To capture the overall user experience of the page including all of the above information plus additional resource requests that might be triggered during the execution of dependent resources, the `page-load` transaction duration might not always reflect the [Load](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event) event of the browser and can extend beyond the event. + +If you are interested in accurately measuring the duration of load event, the information can be extracted by using `Fire load event` Span or from the Transaction marks available as `transaction.marks.agent.domComplete` in the Elasticsearch document. + +::::{note} +The page load transaction is measured relative to the `fetchStart` timestamp from the Navigation Timing API. +:::: + + + +## User-centric Metrics [user-centric-metrics] + +To understand the performance characteristics of a web page beyond the page load and how the user perceives performance, the agent supports capturing these [responsiveness metrics](https://web.dev/user-centric-performance-metrics/). + +`First contentful paint (FCP)` +: Focusses on the initial rendering and measures the time from when the page starts loading to when any part of the page’s content is displayed on the screen. The agent uses the [Paint timing API](https://www.w3.org/TR/paint-timing/#first-contentful-paint) available in the browser to capture the timing information. FCP is captured as transaction mark for `page-load` transaction for all chromium-based browsers (Chrome >60, Edge >79, Opera >47, etc.). + +`Largest contentful paint (LCP)` +: A new page-load metric that denotes the time from when the page starts loading to when the critical element (largest text, image, video elements) is displayed on the screen. LCP is available in the browser through [LargestContentfulPaint API](https://wicg.github.io/largest-contentful-paint/) which relies on the draft [Element Timing API](https://wicg.github.io/element-timing/). LCP is one of the [core web vitals](https://web.dev/vitals/) metrics and available only in Chrome >77. Captured as transaction mark for `page-load` transaction, maintain LCP within the first **2.5 seconds** of page-load to provide a good user experience. + +Interaction to next paint (INP) +: INP quantifies responsiveness to user interactions. The INP value comes from measuring the latency of all click, tap, and keyboard interactions that happen throughout a single page visit and choosing the longest interaction observed. INP is one of the [core web vitals](https://web.dev/vitals/) metrics, and you can read more about INP in the [web.dev docs](https://web.dev/articles/inp). To provide a good user experience, Google recommends an INP of **fewer than 200 milliseconds**. + +`First input delay (FID)` +: FID quantifies the experience of the user when they interact with the page during the page load. It is measured as the time between when a user first interacts with your site (mouse clicks, taps, select dropdowns, etc.) to the time when the browser can respond to that interaction. FID is one of the [core web vitals](https://web.dev/vitals/) metrics and available only in Chrome >85 via [Event Timing API](https://wicg.github.io/event-timing/). FID is captured as `First Input Delay` span for `page-load` transaction. Maintain FID **below 100 milliseconds** to provide a good user experience. + +`Total blocking time (TBT)` +: The sum of the blocking time (duration above 50 ms) for each long task that occurs between the First contentful paint and the time when the transaction is completed. [Total blocking time](https://web.dev/tbt/) is a great companion metric for [Time to interactive](https://web.dev/tti/) (TTI) which is lab metric and not available in the field through browser APIs. The agent captures TBT based on the number of long tasks that occurred during the page load lifecycle. Captured as `Total Blocking Time` span for `page-load` transaction. + +`Cumulative layout shift (CLS)` +: Metric that represents the cumulative score of all unexpected layout shifts that occur during the entire lifespan of the page. CLS is one of the [core web vitals](https://web.dev/vitals/) metrics and here is [how the score is calculated by Chrome](https://web.dev/cls/#layout-shift-score). Maintain a score of **less than 0.1** to provide a good user experience. + +`Long Tasks` +: A long task is any user activity or browser task that monopolize the UI thread for extended periods (greater than 50 milliseconds) and block other critical tasks (frame rate or input latency) from being executed. The agent uses the [Long Task API](https://www.w3.org/TR/longtasks/) which is only available in chromium-based browsers (Chrome >58, Edge >79, Opera >69). Captured as `Longtask` span for all managed transactions. Learn more about [long task spans](/reference/longtasks.md), and how to interpret them. + +`User Timing` +: The [User Timing](https://www.w3.org/TR/user-timing/) spec exposes API for developers to add custom performance entries to their web application. These custom metrics allow users to measure the hot paths of the app code that helps to identify a good user experience. RUM agent records all of the [performance.measure](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMeasure) calls as spans by their measure name in the waterfall for all managed transactions. + + +## User Interactions [user-interactions] + +The RUM agent automatically instruments click event listeners that are registered by the application. The click events are captured as `user-interaction` transactions. However, to avoid sending too many `user-interaction` transactions to the server, the agent discards transactions with no spans (e.g. no network activity). Furthermore, if the click interaction results in route change, then a `route-change` transaction would be captured instead. + +The transaction name can be influenced either by using the `name` or preferably the `data-transaction-name` HTML attribute. Examples of transaction names based on the html attributes present: + +* ``: `Click - button` +* ``: `Click - button["purchase"]` +* ``: `Click - purchase` + + +## Single Page Applications [spa] + +All history `pushState` events will be captured as transactions. Most of these transactions can be enhanced by using framework specific integrations. For all unsupported frameworks/libraries, you can instrument the application by creating [custom transactions](/reference/custom-transactions.md) and custom spans with the [span API](/reference/agent-api.md#apm-start-span). + + +## Frameworks [frameworks] + +The agent supports [integrations with certain frameworks](/reference/framework-specific-integrations.md). + +To instrument custom metrics, like rendering time or mounting time of components on frameworks like React, Angular, Vue, etc., use the [custom transactions API](/reference/custom-transactions.md). + +The core RUM agent supports websites based on multi-page (MPA) and single-page architectures (SPA). The core RUM agent can be used on its own with SPA sites, but we recommend using our framework-specific integrations for the following reasons: + +* **Pages are better grouped by routes**: This results in the `transaction.name` field mapping to the actual application route path declared in the SPA application. +* **Exact SPA navigation rendering**: Integration packages hook into the component lifecycle and measure the duration of the SPA transaction correctly. The core RUM agent is unable to determine when an SPA navigation is rendered and instead waits for the last network request before considering the SPA transition is finished. +* **Improved error capturing**: For example, when an error is thrown inside an Angular application, the framework integration will automatically capture it. The core RUM agent, however, is unable to capture the error as the default error handler doesn’t rethrow the error as a browser event. + + +## Platforms [platforms] + +The following platforms are supported: + +:::{image} ../images/compatibility.png +:alt: Elastic APM RUM Agent compatibility +::: + diff --git a/docs/reference/toc.yml b/docs/reference/toc.yml new file mode 100644 index 000000000..d4be8030f --- /dev/null +++ b/docs/reference/toc.yml @@ -0,0 +1,31 @@ +project: 'APM Real User Monitoring (RUM) JavaScript Agent reference' +toc: + - file: index.md + - file: set-up-apm-real-user-monitoring-javascript-agent.md + children: + - file: install-agent.md + - file: configuring-cors.md + - file: supported-technologies.md + - file: configuration.md + - file: api-reference.md + children: + - file: agent-api.md + - file: transaction-api.md + - file: span-api.md + - file: source-maps.md + - file: framework-specific-integrations.md + children: + - file: react-integration.md + - file: angular-integration.md + - file: vue-integration.md + - file: distributed-tracing.md + - file: breakdown-metrics.md + - file: opentracing.md + - file: advanced-topics.md + children: + - file: longtasks.md + - file: typescript.md + - file: custom-transaction-name.md + - file: custom-transactions.md + - file: performance-tuning.md + - file: upgrading.md \ No newline at end of file diff --git a/docs/reference/transaction-api.md b/docs/reference/transaction-api.md new file mode 100644 index 000000000..dd994d041 --- /dev/null +++ b/docs/reference/transaction-api.md @@ -0,0 +1,140 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/transaction-api.html +--- + +# Transaction API [transaction-api] + +A transaction groups multiple spans in a logical group. + +To start a transaction, you need to call [`apm.startTransaction()`](/reference/agent-api.md#apm-start-transaction). + +To see an example of using custom transactions, see the [Custom Transactions](/reference/custom-transactions.md) article. + + +## `transaction.name` [transaction-name] + +* **Type:** String +* **Default:** `Unknown` + +The name of the transaction. + +Can be used to set or overwrite the name of the transaction (visible in the performance monitoring breakdown). + + +## `transaction.type` [transaction-type] + +* **Type:** String +* **Default:** `custom` + +The type of the transaction. + + +## `transaction.timestamp` [transaction-timestamp] + +* **Type:** String +* **Default:** `undefined` + +The timestamp of the transaction. If the transaction timestamp is not provided (the default behaviour), it will be set by the apm-server (v6.3+). You can, however, set the timestamp on the client (using `new Date().toISOString()`), but you should be aware that the timestamp will reflect the client’s local time which might not always be accurate. + + +## `transaction.startSpan([name][, type][, options])` [transaction-start-span] + +```js +const span = transaction.startSpan('My custom span') +``` + +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. + + +When a span is started it will measure the time until [`span.end()`](/reference/span-api.md#span-end) is called. Blocked spans allow users to control the early closing of [managed transactions](/reference/custom-transactions.md#custom-managed-transactions) in some cases. + +See also the [Span API](/reference/span-api.md) docs for details on how to use custom spans. + + +## `transaction.block(flag)` [transaction-block] + +```js +transaction.block(true) +``` + +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. + +Most of the time, users shouldn’t need to block the running transaction as the agent tries to account for all of the async network activity and capture the required information. The block API is useful when you think auto instrumented code misses important activity and prematurely ends a transaction. An example of this might be a page that contains lots of asynchronous tasks that cannot be automatically instrumented, like web workers. + +```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) +``` + +One can also achieve a similar action by creating blocked spans. Check the [managed transactions](/reference/custom-transactions.md#custom-managed-transactions) guide to learn more. + + +## `transaction.addLabels()` [transaction-add-labels] + +```js +transaction.addLabels({ [name]: value }) +``` + +Add several labels on the transaction. If an error happens during the transaction, it will also get tagged with the same labels. + +Labels are key/value pairs that are indexed by Elasticsearch and therefore searchable (as opposed to data set via [`apm.setCustomContext()`](/reference/agent-api.md#apm-set-custom-context)). + +::::{tip} +Before using custom labels, ensure you understand the different types of [metadata](docs-content://solutions/observability/apps/elastic-apm-events-intake-api.md#apm-api-metadata-overview) that are available. +:::: + + +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. + +::::{warning} +Avoid defining too many user-specified tags. Defining too many unique fields in an index is a condition that can lead to a [mapping explosion](docs-content://manage-data/data-store/mapping.md#mapping-limit-settings). +:::: + + + +## `transaction.end()` [transaction-end] + +```js +transaction.end() +``` + +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. + + +## `transaction.mark(key)` [transaction-mark] + +```js +transaction.mark(key) +``` + +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. + +Arguments: + +* `key` - Any string. All periods (.), asterisks (*), and double quotation marks (") will be replaced by underscores (_), as those characters have special meaning in Elasticsearch + diff --git a/docs/reference/typescript.md b/docs/reference/typescript.md new file mode 100644 index 000000000..a87bfa58f --- /dev/null +++ b/docs/reference/typescript.md @@ -0,0 +1,9 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/typescript.html +--- + +# Using with TypeScript [typescript] + +RUM agent publishes the type definitions for the `@elastic/apm-rum` package via `types` property in `package.json`. If you are importing the package on a TypeScript codebase, you will get automatic code completion, hover info and method signature information on supported platforms (Visual Studio Code, etc) + diff --git a/docs/reference/upgrading.md b/docs/reference/upgrading.md new file mode 100644 index 000000000..69a784f87 --- /dev/null +++ b/docs/reference/upgrading.md @@ -0,0 +1,42 @@ +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/upgrading.html +--- + +# Upgrading [upgrading] + +Upgrades between minor versions of the agent, like from 3.1 to 3.2 are always backwards compatible. Upgrades that involve a major version bump often come with some backwards incompatible changes. + +Before upgrading the agent, be sure to review the: + +* [Agent release notes](/release-notes/index.md) +* [Agent and Server compatibility chart](docs-content://solutions/observability/apps/apm-agent-compatibility.md) + +The following upgrade guides are also available: + +* [Upgrade to version 5.x](/release-notes/breaking-changes.md) - Follow this guide to upgrade from version `4.x` to version `5.x` of the Elastic APM RUM JS Agent. + + +## End of life dates [end-of-life-dates] + +We love all our products, but sometimes we must say goodbye to a release so that we can continue moving forward on future development and innovation. Our [End of life policy](https://www.elastic.co/support/eol) defines how long a given release is considered supported, as well as how long a release is considered still in active development or maintenance. The table below is a simplified description of this policy. + +| Agent version | EOL Date | Maintained until | +| --- | --- | --- | +| 4.8.x | 2021-08-13 | 4.9.0 | +| 4.7.x | 2021-07-15 | 4.8.0 | +| 4.6.x | 2021-05-19 | 4.7.0 | +| 4.5.x | 2021-03-30 | 4.6.0 | +| 4.4.x | 2021-02-05 | 4.5.0 | +| 4.3.x | 2021-01-11 | 4.4.0 | +| 4.2.x | 2021-01-08 | 4.3.0 | +| 4.1.x | 2020-12-12 | 4.2.0 | +| 4.0.x | 2020-09-11 | 4.1.0 | +| 3.0.x | 2020-07-29 | 5.0.0 | +| 2.3.x | 2020-06-18 | 4.0.0 | +| 2.2.x | 2020-06-05 | 2.3.0 | +| 2.1.x | 2020-06-03 | 2.2.0 | +| 2.0.x | 2020-05-14 | 2.1.0 | +| 1.0.x | 2020-02-23 | 3.0.0 | + + diff --git a/docs/vue-integration.asciidoc b/docs/reference/vue-integration.md similarity index 62% rename from docs/vue-integration.asciidoc rename to docs/reference/vue-integration.md index 210ad327d..13518b4ce 100644 --- a/docs/vue-integration.asciidoc +++ b/docs/reference/vue-integration.md @@ -1,49 +1,49 @@ -[[vue-integration]] -=== Vue integration +--- +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/vue-integration.html +--- + +# Vue integration [vue-integration] This document covers how to use Real User Monitoring JavaScript agent with Vue applications. -[[vue-supported-versions]] -==== Supported versions +## Supported versions [vue-supported-versions] This integration supports Vue.js versions ≥ 3.0 +::::{note} +If you are using an Vuejs version < 3.0, use @elastic/apm-rum-vue 1.x to instrument your application. Details are available in a [prior release](https://www.elastic.co/guide/en/apm/agent/rum-js/4.x/vue-integration.html). +:::: -NOTE: If you are using an Vuejs version < 3.0, use @elastic/apm-rum-vue 1.x to instrument your application. Details are available in a https://www.elastic.co/guide/en/apm/agent/rum-js/4.x/vue-integration.html[prior release]. -[[installing-vue-integration]] -==== Installing Elastic APM Vue package +## Installing Elastic APM Vue package [installing-vue-integration] Install the `@elastic/apm-rum-vue` package as a dependency to your application: -[source,bash] ----- +```bash npm install --save @elastic/apm-rum-vue ----- +``` + + +### Using APM Plugin [_using_apm_plugin] -[float] -==== Using APM Plugin -[source,js] ----- +```js app.use(ApmVuePlugin, options) ----- +``` -===== Options +### Options [_options] -* `config` (required) - RUM agent <>. +* `config` (required) - RUM agent [configuration options](/reference/configuration.md). * `router` (optional) - Instance of Vue Router. If provided, will start capturing both page load and SPA navigation events as transactions with path of the route as its name. -* `captureErrors` (optional) - If enabled, will install a global Vue error handler to capture render errors inside the components. Defaults to `true`. - The plugin captures the component name, lifecycle hook and file name (if it's available) as part of the error context. +* `captureErrors` (optional) - If enabled, will install a global Vue error handler to capture render errors inside the components. Defaults to `true`. The plugin captures the component name, lifecycle hook and file name (if it’s available) as part of the error context. -[float] -==== Instrumenting your Vue application +### Instrumenting your Vue application [_instrumenting_your_vue_application] The package exposes `ApmVuePlugin` which is a Vue Plugin and can be installed in your application using `Vue.use` method. -[source,js] ----- +```js import { createApp, defineComponent, h } from 'vue' import { createRouter, createWebHashHistory } from 'vue-router' import { ApmVuePlugin } from '@elastic/apm-rum-vue' @@ -71,16 +71,14 @@ createApp(App) }) // app specific code .mount('#app') ----- +``` -[float] -==== Accessing agent instance inside components +### Accessing agent instance inside components [_accessing_agent_instance_inside_components] Instance of the agent can be accessed inside all the components using `this.$apm` -[source,html] ----- +```html @@ -100,12 +98,11 @@ export default { } } ----- +``` -In case of both SFC and Composition API usage via the recommended ` ----- +``` + +`ApmVuePlugin` expects the router option to be an instance of VueRouter since it uses the [navigation guards](https://next.router.vuejs.org/guide/advanced/navigation-guards.html) functionality. + +Once the plugin is initialized, both page load and SPA navigation events will be captured as transactions with the `path` of the route as its name and `page-load` or `route-change` as type. + -`ApmVuePlugin` expects the router option to be an instance of VueRouter since it uses the -https://next.router.vuejs.org/guide/advanced/navigation-guards.html[navigation guards] functionality. -Once the plugin is initialized, both page load and SPA navigation events will be captured -as transactions with the `path` of the route as its name and `page-load` or `route-change` as type. diff --git a/docs/release-notes.asciidoc b/docs/release-notes.asciidoc deleted file mode 100644 index ac448153f..000000000 --- a/docs/release-notes.asciidoc +++ /dev/null @@ -1,17 +0,0 @@ -:pull: https://github.com/elastic/apm-agent-rum-js/pull/ -:issue: https://github.com/elastic/apm-agent-rum-js/issues/ -:commit: https://github.com/elastic/apm-agent-rum-js/commit/ - -[[release-notes]] -== Release notes - -All notable changes to this project will be documented here. - -* <> -* <> -* <> -* <> -* <> -* <> - -include::../CHANGELOG.asciidoc[] \ No newline at end of file diff --git a/docs/release-notes/breaking-changes.md b/docs/release-notes/breaking-changes.md new file mode 100644 index 000000000..d004dfeda --- /dev/null +++ b/docs/release-notes/breaking-changes.md @@ -0,0 +1,116 @@ +--- +navigation_title: "Elastic APM Real User Monitoring JavaScript Agent" +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/upgrade-to-v5.html +--- + +# Elastic APM Real User Monitoring JavaScript Agent breaking changes [elastic-apm-real-user-monitoring-javascript-agent-breaking-changes] +Before you upgrade, carefully review the Elastic APM Real User Monitoring JavaScript Agent breaking changes and take the necessary steps to mitigate any issues. + +% To learn how to upgrade, check out . + +% ## Next version [elastic-apm-real-user-monitoring-javascript-agent-nextversion-breaking-changes] +% **Release date:** Month day, year + +% ::::{dropdown} Title of breaking change +% Description of the breaking change. +% For more information, check [PR #](PR link). +% **Impact**
Impact of the breaking change. +% **Action**
Steps for mitigating deprecation impact. +% :::: + +## 5.15.0 [elastic-apm-real-user-monitoring-javascript-agent-5150-breaking-changes] +**Release date:** September 27, 2023 + +Previously, there was a start time discrepancy between sampled and unsampled page load transactions, which was wrong. From now on, the agent will set the same start time for both of them. +Custom dashboards built using the page load duration will see an effect with the solution. + +For more information, check [#1435](https://github.com/elastic/apm-agent-rum-js/pull/1435). + +## 5.13.0 [elastic-apm-real-user-monitoring-javascript-agent-5130-breaking-changes] +**Release date:** July 19, 2023 + +* Previously, breakdown timings were reported as milliseconds values in the `span.self_time.sum.us field`, which was wrong. From now on, it will be reported as microsecond values to match the APM specification. For more information, check [#1381](https://github.com/elastic/apm-agent-rum-js/pull/1381). +* The metrics `transaction.duration.sum.us`, `transaction.duration.count` and `transaction.breakdown.count` are no longer recorded. For more information, check [#1382](https://github.com/elastic/apm-agent-rum-js/pull/1382). + +## 5.0.0 [elastic-apm-real-user-monitoring-javascript-agent-500-breaking-changes] +**Release date:** March 18, 2020 + +Upgrading from version `4.x` to `5.x` of the RUM Agent introduces some breaking changes. + +### Global labels are only added to metadata to improve payload size +For more information, check [#618](https://github.com/elastic/apm-agent-rum-js/issues/618). + +### Labels now accept Boolean and Number types +For more information, check [#272](https://github.com/elastic/apm-agent-rum-js/issues/272). + +### Agent name changed to `rum-js` +The Agent name has been changed to `rum-js`. Because older versions of the APM app in Kibana don’t recognize this new name, you may need to upgrade your Elastic stack version. + +For more information, check [#379](https://github.com/elastic/apm-agent-rum-js/issues/379). + +### Official W3C tracecontext support +The RUM Agent supports the official W3C tracecontext `traceparent` header, instead of the previously used `elastic-apm-traceparent` header. If you’re using Elastic backend agents, you must upgrade them to a version that also supports the official W3C tracecontext headers. + +For more information, check [#477](https://github.com/elastic/apm-agent-rum-js/issues/477). + +### `addTags` replaced with `addLabels +`addTags`, which was deprecated in version `4.1`, has been removed and replaced with `addLabels`, which supports strings, booleans, and numbers: + +* `apm.addTags()` removed in favor of [`apm.addLabels()`](/reference/agent-api.md#apm-add-labels). +* `span.addTags()` removed in favor of [`span.addLabels()`](/reference/span-api.md#span-add-labels). +* `transaction.addTags()` removed in favor of [`transaction.addLabels()`](/reference/transaction-api.md#transaction-add-labels). + +For more information, check [#215](https://github.com/elastic/apm-agent-rum-js/issues/215). + +### Single queue processing +A single queue is now used to process all events (transactions, errors, etc.). This change allows the consolidation of four configuration options into one: + +Removed options: + +* `errorThrottleLimit` +* `errorThrottleInterval` +* `transactionThrottleLimit` +* `transactionThrottleInterval` + +Added option: + +* [`eventsLimit`](/reference/configuration.md#events-limit) — Configure the number of events sent to APM Server per minute. Defaults to `80`. + +For more information, check [#628](https://github.com/elastic/apm-agent-rum-js/issues/628). + +## Upgrade steps [v5-upgrade-steps] + +### Upgrade APM Server [v5-upgrade-server] +Version `5.x` of the RUM Agent requires APM Server version >= `7.0`. The [APM Server `7.0` upgrade guide](https://www.elastic.co/guide/en/apm/guide/7.17/upgrading-to-70.html) can help with the upgrade process. + +::::{note} +APM Server version >= `7.0` requires Elasticsearch and Kibana versions >= `7.0` as well. +:::: + +### Upgrade backend agents [v5-upgrade-agents] +All Elastic APM agents have been upgraded to support the changes in the RUM Agent. You must upgrade your backend agents to the minimum versions listed below for all features to work: + +| Agent name | Agent Version | +| --- | --- | +| **Go Agent** | >= `1.6` | +| **Java Agent** | >= `1.14` | +| **.NET Agent** | >= `1.3` | +| **Node.js Agent** | >= `3.4` | +| **Python Agent** | >= `5.4` | +| **Ruby Agent** | >= `3.5` | + +### Upgrade the RUM agent [v5-update-rum-agent] +Update or download the latest version of the RUM Agent using your [preferred installation method](/reference/install-agent.md). + +If your old configuration used one of the removed config options (listed below), update your configuration to use the new config options instead. + +Removed configurations: + +* `errorThrottleLimit` removed in favor of [`eventsLimit`](/reference/configuration.md#events-limit). +* `errorThrottleInterval` removed in favor of [`eventsLimit`](/reference/configuration.md#events-limit). +* `transactionThrottleLimit` removed in favor of [`eventsLimit`](/reference/configuration.md#events-limit). +* `transactionThrottleInterval` removed in favor of [`eventsLimit`](/reference/configuration.md#events-limit). +* `apm.addTags()` removed in favor of [`apm.addLabels()`](/reference/agent-api.md#apm-add-labels). +* `span.addTags()` removed in favor of [`span.addLabels()`](/reference/span-api.md#span-add-labels). +* `transaction.addTags()` removed in favor of [`transaction.addLabels()`](/reference/transaction-api.md#transaction-add-labels). diff --git a/docs/release-notes/index.md b/docs/release-notes/index.md new file mode 100644 index 000000000..0a4b83bf4 --- /dev/null +++ b/docs/release-notes/index.md @@ -0,0 +1,286 @@ +--- +navigation_title: "Elastic APM Real User Monitoring JavaScript Agent" +mapped_pages: + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/release-notes-5.x.html + - https://www.elastic.co/guide/en/apm/agent/rum-js/current/release-notes.html +--- +# Elastic APM Real User Monitoring JavaScript Agent release notes [elastic-apm-rum-javascript-agent-release-notes] + +Review the changes, fixes, and more in each version of Elastic APM Real User Monitoring JavaScript Agent. + +To check for security updates, go to [Security announcements for the Elastic stack](https://discuss.elastic.co/c/announcements/security-announcements/31). + +% Release notes includes only features, enhancements, and fixes. Add breaking changes, deprecations, and known issues to the applicable release notes sections. + +% ## version.next [elastic-apm-rum-javascript-agent-versionext-release-notes] +% **Release date:** Month day, year + +% ### Features and enhancements [elastic-apm-rum-javascript-agent-versionext-features-enhancements] + +% ### Fixes [elastic-apm-rum-javascript-agent-versionext-fixes] + +## 5.16.1 [elastic-apm-rum-javascript-agent-5161-release-notes] +**Release date:** June 27, 2024 + +### Fixes [elastic-apm-rum-javascript-agent-5161-fixes] +* User interaction click transactions will report correct transaction names for IE11 [#1511](https://github.com/elastic/apm-agent-rum-js/pull/1511) + +## 5.16.0 [elastic-apm-rum-javascript-agent-5160-release-notes] +**Release date:** December 27, 2023 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5160-features-enhancements] +* Add Support for [Interaction to Next Paint (INP) metric](https://web.dev/articles/inp). This new metric, which replaces FID, will be available in the User Experience App from version 8.12.0 of the Elastic Stack. [#1462](https://github.com/elastic/apm-agent-rum-js/pull/1462) + +## 5.15.0 [elastic-apm-rum-javascript-agent-5150-release-notes] +**Release date:** September 27, 2023 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5150-features-enhancements] +* Capture errors from objects thrown from the promise rejection events including the `reason and custom properties`: [#1428](https://github.com/elastic/apm-agent-rum-js/pull/1428) + +## 5.14.0 [elastic-apm-rum-javascript-agent-5140-release-notes] +**Release date:** August 3, 2023 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5140-features-enhancements] +* Add redirect span to the page-load transaction: [#1400](https://github.com/elastic/apm-agent-rum-js/pull/1400) + +### Fixes [elastic-apm-rum-javascript-agent-5140-fixes] +* Fetch API instrumentation now handles requests with `URL` objects. [#1398](https://github.com/elastic/apm-agent-rum-js/pull/1398) + +## 5.13.0 [elastic-apm-rum-javascript-agent-5130-release-notes] +**Release date:** July 19, 2023 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5130-features-enhancements] +* Support for Angular 16 is made available via `@elastic/apm-rum-angular@3.0.0`: [#1380](https://github.com/elastic/apm-agent-rum-js/pull/1380) +* Improve user-interaction transactions naming. Unsupported browsers: IE11 [#1390](https://github.com/elastic/apm-agent-rum-js/pull/1390) +* Add `apmRequest` and `sendCredentials` config to TypeScript typings: [#1254](https://github.com/elastic/apm-agent-rum-js/pull/1254) [#1243](https://github.com/elastic/apm-agent-rum-js/pull/1243) + +### Fixes [elastic-apm-rum-javascript-agent-5130-fixes] +* Fix warnings where performance entries are not supported: [#1246](https://github.com/elastic/apm-agent-rum-js/pull/1246) + +## 5.12.0 [elastic-apm-rum-javascript-agent-5120-release-notes] +**Release date:** June 14, 2022 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5120-features-enhancements] +* Introduce new config option [`sendCredentials`](/reference/configuration.md#send-credentials). This allows the agent to send cookies to APM servers that are behind reverse proxies that need requests to be authenticated: [#1238](https://github.com/elastic/apm-agent-rum-js/pull/1238) +* Agent now warns users if they provide non-existent config options when initializing it: [#1230](https://github.com/elastic/apm-agent-rum-js/pull/1230) + +### Fixes [elastic-apm-rum-javascript-agent-5120-fixes] +* Capture the stacktrace of a SyntaxError triggered because of a malformed JavaScript code. Before this fix the agent was capturing an empty stacktrace: [#1239](https://github.com/elastic/apm-agent-rum-js/pull/1239) + +## 5.11.1 [elastic-apm-rum-javascript-agent-5111-release-notes] +**Release date:** May 16, 2022 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5111-features-enhancements] +* Span’s outcome is now set to `Unknown` when a Fetch/XHR request is aborted. The outcome can be found in the metadata information of the span details in APM UI: [#1211](https://github.com/elastic/apm-agent-rum-js/pull/1211) +* Allow users the ability to disable compression for the events sent to APM server. This is helpful for debugging purposes while inspecting via Devtools and also for generating HAR file. Please see our [troubleshooting](docs-content://troubleshoot/observability/apm-agent-rum-js/apm-real-user-monitoring-javascript-agent.md#disable-events-payload-compression) guide for more information: [#1214](https://github.com/elastic/apm-agent-rum-js/pull/1214) + +### Fixes [elastic-apm-rum-javascript-agent-5111-fixes] +* The instrumentation of fetch API consumes a response as a readable stream properly. Before this fix the related span was being ended on the start of the response rather than on the end of it: [#1213](https://github.com/elastic/apm-agent-rum-js/pull/1213) +* Agent now can listen to all click events on the page. Users can enable/disable click instrumentation via `disableInstrumentation: ["click"]`. `eventtarget` instrumentation flag will be deprecated in favor of `click` and will be removed in the future releases: [#1219](https://github.com/elastic/apm-agent-rum-js/pull/1219) + +## 5.11.0 [elastic-apm-rum-javascript-agent-5110-release-notes] +**Release date:** April 20, 2022 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5110-features-enhancements] +* Events are now beaconed when the user abandons or backgrounds the page, this makes sure the agent never miss an event. Before this change it was only sending them every interval configurable via `flushInterval`. Unsupported browsers: Firefox, IE11: [#1146](https://github.com/elastic/apm-agent-rum-js/pull/1146) + +::::{note} +Transactions based on the [supported technologies](/reference/supported-technologies.md) and [custom managed transactions](/reference/custom-transactions.md#custom-managed-transactions) are the only ones taken into account. +:::: + +* **rum-vue:** Introduce script setup syntax support: [#1194](https://github.com/elastic/apm-agent-rum-js/issues/1194) +* Override reuse threshold when redefining a transaction. This will permit the agent not to miss data on slow network connections: [#1196](https://github.com/elastic/apm-agent-rum-js/issues/1196) + +### Fixes [elastic-apm-rum-javascript-agent-5110-fixes] +* Report Largest Contentful Paint (LCP) properly. Before this fix the agent was not giving the browser enough time to capture LCP entries that are post on-load: [#1190](https://github.com/elastic/apm-agent-rum-js/pull/1190) + +## 5.10.2 [elastic-apm-rum-javascript-agent-5102-release-notes] +**Release date:** February 3, 2022 + +### Fixes [elastic-apm-rum-javascript-agent-5102-fixes] +* create user-interaction transactions based on the element on which the event occurred rather than the element on which the event handler has been attached. All web applications that rely on event delegation will benefit from this: [#969](https://github.com/elastic/apm-agent-rum-js/issues/969) + +## 5.10.1 [elastic-apm-rum-javascript-agent-5101-release-notes] +**Release date:** January 10, 2022 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5101-features-enhancements] +* **rum-core:** update Cumulative layout shift(CLS) calculation following the new guidelines from Google: `maximum session window with 1 second gap, capped at 5 seconds.`: [#1033](https://github.com/elastic/apm-agent-rum-js/issues/1033) + +### Fixes [elastic-apm-rum-javascript-agent-5101-fixes] +* **rum-angular:** recover compatibility with Angular 9.0.x: [#1115](https://github.com/elastic/apm-agent-rum-js/issues/1115) + +## 5.10.0 [elastic-apm-rum-javascript-agent-5100-release-notes] +**Release date:** December 7, 2021 + +### Features and enhancements [elastic-apm-rum-javascript-agent-5100-features-enhancements] +* Introduce new config option `serverUrlPrefix` to make the APM server URL configurable: [#1078](https://github.com/elastic/apm-agent-rum-js/issues/1078) +* Expose Transaction, Span, TransactionOptions and SpanOptions types definition: [#1045](https://github.com/elastic/apm-agent-rum-js/issues/1045) and [#995](https://github.com/elastic/apm-agent-rum-js/issues/995) +* Set the values to empty string for deprecated span destination metrics: [#1098](https://github.com/elastic/apm-agent-rum-js/issues/1098) + +### Fixes [elastic-apm-rum-javascript-agent-5100-fixes] +* Check the existence of navigation timing data when compressing transaction marks: [#1104](https://github.com/elastic/apm-agent-rum-js/issues/1104) + +## 5.9.1 [elastic-apm-rum-javascript-agent-591-release-notes] +**Release date:** July 15, 2021 + +### Fixes [elastic-apm-rum-javascript-agent-591-fixes] +* Validate `apmRequest` function is called for every request sent to the APM server when compression is enabled: [#1055](https://github.com/elastic/apm-agent-rum-js/issues/1055) + +## 5.9.0 [elastic-apm-rum-javascript-agent-590-release-notes] +**Release date:** July 13, 2021 + +### Features and enhancements [elastic-apm-rum-javascript-agent-591-features-enhancements] +* Add support for [apmRequest configuration](/reference/configuration.md#apm-request) that allows users to pass a custom function that can be used to modify the request sent to the APM server: [#1018](https://github.com/elastic/apm-agent-rum-js/issues/1018) +* Support for React 17 is made available via `@elastic/apm-rum-react` package: [#1031](https://github.com/elastic/apm-agent-rum-js/issues/1031) +* Support for Angular 12 is made available via `@elastic/apm-rum-angular` package: [#1028](https://github.com/elastic/apm-agent-rum-js/issues/1028) + +### Fixes [elastic-apm-rum-javascript-agent-590-fixes] +* Update incorrect typings for adding labels to transaction and spans: [#1017](https://github.com/elastic/apm-agent-rum-js/issues/1017) + +## 5.8.0 [elastic-apm-rum-javascript-agent-580-release-notes] +**Release date:** April 19, 2021 + +### Features and enhancements [elastic-apm-rum-javascript-agent-590-features-enhancements] +* First draft of session information is added for `page-load` Transactions (disabled by default): [#634](https://github.com/elastic/apm-agent-rum-js/issues/634) + +## 5.7.2 [elastic-apm-rum-javascript-agent-572-release-notes] +**Release date:** April 2, 2021 + +### Fixes [elastic-apm-rum-javascript-agent-572-fixes] +* Transaction marks for the APM server V3 spec was mapped to incorrect field which resulted in Kibana User Expererience App missing some of the core data. This only affects users who had set config `apiVersion` > 2: [#1007](https://github.com/elastic/apm-agent-rum-js/issues/1007) + +## 5.7.1 [elastic-apm-rum-javascript-agent-571-release-notes] +**Release date:** March 17, 2021 + +### Fixes [elastic-apm-rum-javascript-agent-571-fixes] +* Discard buffered longtasks spans from page load transactions getting added to subsequent route change and other auto auto-instrumented transactions resulting in incorrect start time for those transactions: [#989](https://github.com/elastic/apm-agent-rum-js/issues/989) + +## 5.7.0 [elastic-apm-rum-javascript-agent-570-release-notes] +**Release date:** March 15, 2021 + +### Features and enhancements [elastic-apm-rum-javascript-agent-570-features-enhancements] +* Support regular expression for detecting distributed tracing origins (`distributedTracingOrigins`): [#943](https://github.com/elastic/apm-agent-rum-js/issues/943) +* Capture buffered longtask entries: [#964](https://github.com/elastic/apm-agent-rum-js/issues/964) +* Expose agent configuration TypeScript definition: [#979](https://github.com/elastic/apm-agent-rum-js/issues/979) + +## 5.6.3 [elastic-apm-rum-javascript-agent-563-release-notes] +**Release date:** February 2, 2021 + +### Features and enhancements [elastic-apm-rum-javascript-agent-563-features-enhancements] +* Propagate sampling weight through tracestate header: [#845](https://github.com/elastic/apm-agent-rum-js/issues/845) +* Add necessary scripts to load test APM server with RUM payload: [#948](https://github.com/elastic/apm-agent-rum-js/issues/948) + +### Fixes [elastic-apm-rum-javascript-agent-563-fixes] +* Handle null reason in promise rejection event: [#940](https://github.com/elastic/apm-agent-rum-js/issues/940) + +## 5.6.2 [elastic-apm-rum-javascript-agent-562-release-notes] +**Release date:** November 6, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-562-features-enhancements] +* Add transaction sampling rate precision which ensures `transaction_sample_rate` configuration option has a maximum precision of 4 decimal places: [#927](https://github.com/elastic/apm-agent-rum-js/issues/927) +* Add `outcome` field to applicable transactions and spans that is used by the APM UI for displaying the error rate chart: [#904](https://github.com/elastic/apm-agent-rum-js/issues/904) + +## 5.6.1 [elastic-apm-rum-javascript-agent-561-release-notes] +**Release date:** September 29, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-561-features-enhancements] +* Longtasks are now aggregated under the experience field to make querying faster: [#900](https://github.com/elastic/apm-agent-rum-js/issues/900) + +### Fixes [elastic-apm-rum-javascript-agent-561-fixes] +* Check for a Webkit Navigation timing API bug is added to avoid having incorrect navigation marks: [#903](https://github.com/elastic/apm-agent-rum-js/issues/903) + +## 5.6.0 [elastic-apm-rum-javascript-agent-560-release-notes] +**Release date:** September 17, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-560-features-enhancements] +* Add new method signaturtes to the exported type definitions: [#890](https://github.com/elastic/apm-agent-rum-js/issues/890) +* Improve the span creation time when there is an active transaction on page: [#883](https://github.com/elastic/apm-agent-rum-js/issues/883) + +### Fixes [elastic-apm-rum-javascript-agent-560-fixes] +* Frameworks should not be automatically instrumented when the apm is inactive : [#885](https://github.com/elastic/apm-agent-rum-js/issues/885) +* Add default XHR timeout for compressed requests to APM server: [#897](https://github.com/elastic/apm-agent-rum-js/issues/897) +* Measure First Input Delay metrics properly for page load transactions: [#899](https://github.com/elastic/apm-agent-rum-js/issues/899) + +## 5.5.0 [elastic-apm-rum-javascript-agent-550-release-notes] +**Release date:** August 18, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-550-features-enhancements] +* Provide an API to block all auto instrumented transactions created by the agent through `transaction.block` method. Users can also use the `startSpan` API to create blocking spans to control this behaviour: [#866](https://github.com/elastic/apm-agent-rum-js/issues/866) +* Expose options to create blocking spans from the agent API via `startSpan`: [#875](https://github.com/elastic/apm-agent-rum-js/issues/875) +* Capture Cumulative layout shift(CLS), Total blocking time(TBT) and First input delay(FID) as part of experience metrics under page-load transactions: [#838](https://github.com/elastic/apm-agent-rum-js/issues/838) + +### Fixes [elastic-apm-rum-javascript-agent-550-fixes] +* Track various XHR states like timeouts, errors and aborts and end all managed transactions correctly: [#871](https://github.com/elastic/apm-agent-rum-js/issues/871) +* Fix inconsistencies in the XHR timings by removing the task scheduling logic: [#871](https://github.com/elastic/apm-agent-rum-js/issues/871) +* Accept the user provided `logLevel` configuration when agent is not active: [#861](https://github.com/elastic/apm-agent-rum-js/issues/861) +* Opentracing Tracer should return Noop on unsupported platforms: [#872](https://github.com/elastic/apm-agent-rum-js/issues/872)s + +## 5.4.0 [elastic-apm-rum-javascript-agent-540-release-notes] +**Release date:** July 29, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-540-features-enhancements] +* Agent now uses the new CompressionStream API available on modern browsers to gzip compress the payload sent to the APM server. This yields a huge reduction of around ~96% in the payload size for an example web application when compared with the v3 specification: [#572](https://github.com/elastic/apm-agent-rum-js/issues/572) + +## 5.3.0 [elastic-apm-rum-javascript-agent-530-release-notes] +**Release date:** July 6, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-530-features-enhancements] +* Introduced better grouping strategy for all managed transactions based on the current browser’s location by default instead of grouping all transactions under `UNKNOWN` category: [#827](https://github.com/elastic/apm-agent-rum-js/issues/827) +* Capture XHR, Fetch calls as spans that happened before the agent script is downloaded using the browser’s Resource Timing API: [#825](https://github.com/elastic/apm-agent-rum-js/issues/825) +* Populate `span.destination.*` context fields for Navigation Timing span that denotes the HTML downloading phase: [#829](https://github.com/elastic/apm-agent-rum-js/issues/829) +* Use Page Visibility API to discard transactions if the page was backgrounded at any point during the lifetime of the transaction: [#295](https://github.com/elastic/apm-agent-rum-js/issues/295) +* Add `apiVersion` config to TypeScript typings: [#833](https://github.com/elastic/apm-agent-rum-js/issues/833) + +## 5.2.1 [elastic-apm-rum-javascript-agent-521-release-notes] +**Release date:** June 24, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-521-features-enhancements] +* Added support for path array in `` React component that associates the transaction based on the mounted path: [#702](https://github.com/elastic/apm-agent-rum-js/issues/702) + +### Fixes [elastic-apm-rum-javascript-agent-521-fixes] +* Capture Total Blocking Time (TBT) only after all longtask entries are observed: [#803](https://github.com/elastic/apm-agent-rum-js/issues/803) +* Do not capture page load transaction marks when the NavigationTiming data from the browsers are not trustable: [#818](https://github.com/elastic/apm-agent-rum-js/issues/818) + +## 5.2.0 [elastic-apm-rum-javascript-agent-520-release-notes] +**Release date:** May 28, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-520-features-enhancements] +* Agent now supports compressing events payload sent to the APM server via new configuration [apiVersion](/reference/configuration.md#api-version). It yeilds a huge reduction of around ~45% in the payload size for average sized web pages: [#768](https://github.com/elastic/apm-agent-rum-js/issues/768) +* Capture First Input Delay(FID) as Span for page-load transaction: [#732](https://github.com/elastic/apm-agent-rum-js/issues/732) +* Capture Total Blocking Time(TBT) as Span for page-load transaction: [#781](https://github.com/elastic/apm-agent-rum-js/issues/781) +* Refactor ServiceFactory class to use constant service names: [#238](https://github.com/elastic/apm-agent-rum-js/issues/238) + +### Fixes [elastic-apm-rum-javascript-agent-520-fixes] +* Allow setting labels before agent is initialized: [#780](https://github.com/elastic/apm-agent-rum-js/issues/780) +* Use single instance of apm across all packages: [#791](https://github.com/elastic/apm-agent-rum-js/issues/791) +* User defined types for managed transactions are considered of high precedence: [#758](https://github.com/elastic/apm-agent-rum-js/issues/758) +* Add span subtype information in payload without camelcasing: [#753](https://github.com/elastic/apm-agent-rum-js/issues/753) +* Treat truncated spans percentage as regular span in breakdown calculation: [#776](https://github.com/elastic/apm-agent-rum-js/issues/776) + +## 5.1.1 [elastic-apm-rum-javascript-agent-511-release-notes] +**Release date:** April 15, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-511-features-enhancements] +* Performance Observer is used to measure FirstContentfulPaint Metric: [#731](https://github.com/elastic/apm-agent-rum-js/issues/731) + +### Fixes [elastic-apm-rum-javascript-agent-511-fixes] +* Avoid full component re-rerender when query params are updated on current `ApmRoute` inside child components: [#748](https://github.com/elastic/apm-agent-rum-js/issues/748) + +## 5.1.0 [elastic-apm-rum-javascript-agent-510-release-notes] +**Release date:** April 8, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-510-features-enhancements] +* Route change transactions now includes the browsers next paint frame: [#404](https://github.com/elastic/apm-agent-rum-js/issues/404) +* Support differential loading with Angular CLI: [#607](https://github.com/elastic/apm-agent-rum-js/issues/607) +* Reduced the bundle size by modifying the random number generator algorithm: [#705](https://github.com/elastic/apm-agent-rum-js/issues/705) + +### Fixes [elastic-apm-rum-javascript-agent-510-fixes] +* Handle when errors are thrown in unsupported browsers: [#707](https://github.com/elastic/apm-agent-rum-js/issues/707) +* Captured API calls are duplicated as spans in IE: [#723](https://github.com/elastic/apm-agent-rum-js/issues/723) + +## 5.0.0 [elastic-apm-rum-javascript-agent-500-release-notes] +**Release date:** March 18, 2020 + +### Features and enhancements [elastic-apm-rum-javascript-agent-500-features-enhancements] +* Monitor longtasks by default during active transaction: [#601](https://github.com/elastic/apm-agent-rum-js/issues/601) +* Set sync field only for synchronous spans: [#619](https://github.com/elastic/apm-agent-rum-js/issues/619) diff --git a/docs/release-notes/known-issues.md b/docs/release-notes/known-issues.md new file mode 100644 index 000000000..5de4abc70 --- /dev/null +++ b/docs/release-notes/known-issues.md @@ -0,0 +1,19 @@ +--- +navigation_title: "Elastic APM Real User Monitoring JavaScript Agent" + +--- +# Elastic APM Real User Monitoring JavaScript Agent known issues [elastic-apm-rum-javascript-agent-known-issues] + +% Use the following template to add entries to this page. + +% :::{dropdown} Title of known issue +% **Details** +% On [Month/Day/Year], a known issue was discovered that [description of known issue]. + +% **Workaround** +% Workaround description. + +% **Resolved** +% On [Month/Day/Year], this issue was resolved. + +::: \ No newline at end of file diff --git a/docs/release-notes/toc.yml b/docs/release-notes/toc.yml new file mode 100644 index 000000000..7000d42b9 --- /dev/null +++ b/docs/release-notes/toc.yml @@ -0,0 +1,4 @@ +toc: + - file: index.md + - file: known-issues.md + - file: breaking-changes.md \ No newline at end of file diff --git a/docs/set-up.asciidoc b/docs/set-up.asciidoc deleted file mode 100644 index 33b0793db..000000000 --- a/docs/set-up.asciidoc +++ /dev/null @@ -1,193 +0,0 @@ -[[getting-started]] -== Set up the Agent - -To start reporting your web page performance to Elastic APM, -you must first {observability-guide}/apm-configuration-rum.html[enable the RUM endpoint] in your `apm-server` configuration. - -Once the APM Server endpoint has been configured, you can: - -* <> -* <> - -[[install-the-agent]] -=== Install the Agent - -There are multiple ways to add the APM RUM Agent to your web page: - -* <>: Add a ` - ----- - -==== Asynchronous / Non-Blocking Pattern - -Loading the script asynchronously ensures the agent script will not block other -resources on the page, however, it will still block browsers `onload` event. - -[source,html] ----- - ----- - -Even though this is the recommended pattern, there is a caveat to be aware of. -Because the downloading and initializing of the agent happens asynchronously, -distributed tracing will not work for requests that occur before the agent is initialized. - -NOTE: Please download the latest version of RUM agent from https://github.com/elastic/apm-agent-rum-js/releases/latest[GitHub] or -https://unpkg.com/@elastic/apm-rum/dist/bundles/elastic-apm-rum.umd.min.js[UNPKG] -and host the file in your Server/CDN before deploying to production. Remember to -use a proper versioning scheme and set a far future `max-age` and `immutable` -in the https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control[cache-control] -header, as the file never changes. - -The debug messages are removed by default from the minified bundles. It is strongly recommended -to use the unminified version for debugging purposes. - -[float] -[[using-bundlers]] -=== Using Bundlers - -Install the Real User Monitoring APM agent as a dependency to your application: - -[source,bash] ----- -npm install @elastic/apm-rum --save ----- - -Configure the agent: - -[source,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: '' -}) ----- - -[float] -[[production-build]] -==== Production Build - -By default, RUM agent logs all the debug messages to the browser console. These -logs are very useful in development. However, they make the RUM agent bundle -size larger so you should make sure to use the optimized production version when deploying your application. - -You can find instructions for building optimized code below for different bundlers. - -[float] -==== Webpack -For optimized webpack production build, include the Environment/Define plugin in the webpack configuration. - -[source, js] ----- -const { EnvironmentPlugin } = require('webpack') - -plugins: [ - new EnvironmentPlugin({ - NODE_ENV: 'production' - }) -] ----- - -You can learn more about this in https://webpack.js.org/plugins/environment-plugin[Webpack documentation]. - -[float] -==== Rollup - -For optimized rollup production build, include the replace plugin which ensures the right build environment is used. - -[source, js] ----- -const replace = require('rollup-plugin-replace') - -plugins: [ - replace({ - 'process.env.NODE_ENV': JSON.stringify('production') - }) -] ----- - -NOTE: Currently the optimized (minified + gzipped) agent bundle size is about 16KiB. - -[[configuring-cors]] -=== Configure CORS - -If APM Server is deployed in an origin different than the page's origin, -you will need to configure Cross-Origin Resource Sharing (CORS). - -A list of permitted origins can be supplied to the -{observability-guide}/apm-configuration-rum.html#apm-rum-allow-origins[`apm-server.rum.allow_origins`] -configuration option. -By default, APM Server allows all origins. - -[float] -==== How CORS works - -When the RUM agent makes its initial `POST` request, the browser will check to see if it is a cross-origin request. -If it is, the browser automatically makes a preflight `OPTIONS` request to the server to ensure the original `POST` request is allowed. -If this `OPTIONS` check passes, then the original `POST` request is allowed. -This request will fail if RUM support is not configured in the APM Server. - -If you use a proxy, the preflight request headers may be necessary for your configuration: - -[source,js] ----- -Access-Control-Request-Headers: Content-Type -Access-Control-Request-Method: POST -Origin: [request-origin] ----- - -The response should include these headers: - -[source,js] ----- -Access-Control-Allow-Headers: Content-Type -Access-Control-Allow-Methods: POST, OPTIONS -Access-Control-Allow-Origin: [request-origin] ----- - -If you enable the <> configuration option, your proxy's response must include the header `Access-Control-Allow-Origin` with the page's origin as a value, and the following header: - -[source,js] ----- -Access-Control-Allow-Credentials: true ----- - -TIP: To learn more about CORS, see the MDN page on -https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS[Cross-Origin Resource Sharing]. diff --git a/docs/sourcemap.asciidoc b/docs/sourcemap.asciidoc deleted file mode 100644 index a26515c33..000000000 --- a/docs/sourcemap.asciidoc +++ /dev/null @@ -1,26 +0,0 @@ -[[sourcemap]] -== Source maps - -Minifying JavaScript bundles is a common practice in production as it can improve the load time and network latency of your application. -However, minified code by itself can be hard to debug. -For this reason, Elastic APM supports source maps. -A source map is a file that maps minified files back to the original source code, -allowing you to maintain the speed advantage of minified code, -without losing the ability to quickly and easily debug your applications. - -There are three steps required to enable, upload, and apply a source map to error stack traces. -An overview is listed below, and a complete walk-through is available in the -{observability-guide}/apm-source-map-how-to.html[generate and upload a source map] guide. - -1. Set the <> when initializing the RUM Agent. -2. {observability-guide}/apm-source-map-how-to.html#apm-source-map-rum-generate[Generate a source map] -for your application with the `serviceVersion` from step one. -3. {observability-guide}/apm-source-map-how-to.html#apm-source-map-rum-upload[Enable and upload the source map file] to APM Server. - -// Don't link to this section -[[secret-token]] -You can also configure a {observability-guide}/apm-secret-token.html[secret token] or -{observability-guide}/apm-api-key.html[API key] to restrict the uploading of sourcemaps. - -TIP: Don't forget, -you must enable {observability-guide}/apm-configuration-rum.html[RUM support] in the APM Server for this endpoint to work. diff --git a/docs/span-api.asciidoc b/docs/span-api.asciidoc deleted file mode 100644 index bdeb244da..000000000 --- a/docs/span-api.asciidoc +++ /dev/null @@ -1,69 +0,0 @@ -[[span-api]] - -=== `Span` API - -A span measures the duration of a single event. -When a span is created it will measure the time until <> is called. - -To get a `Span` object, -you need to call <>. - -[float] -[[span-name]] -==== `span.name` - -* *Type:* String -* *Default:* `Unknown` - -The name of the span. -This can also be set via <>. - - -[float] -[[span-type]] -==== `span.type` - -* *Type:* String -* *Default:* `custom` - -The type of span. -This can also be set via <>. - -The type is a hierarchical string used to group similar spans together. -For instance, all outgoing AJAX requests are given the type `external.http`. - -In the above example, `external` is considered the type prefix. -Though there are no naming restrictions for this prefix, -the following are standardized across all Elastic APM agents: -`app`, `db`, `cache`, `template`, and `external`. - - -[float] -[[span-add-labels]] -==== `span.addLabels()` - -[source,js] ----- -span.addLabels({ [name]: value }) ----- - -Add several labels on the span. If an error happens during the span, -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. - -[float] -[[span-end]] -==== `span.end()` - -[source,js] ----- -span.end() ----- - -Ends the span. If the span has already ended, nothing happens. diff --git a/docs/supported-technologies.asciidoc b/docs/supported-technologies.asciidoc deleted file mode 100644 index 10f1a60c1..000000000 --- a/docs/supported-technologies.asciidoc +++ /dev/null @@ -1,142 +0,0 @@ -[[supported-technologies]] -== Supported Technologies - -[float] -[[page-load-metrics]] -=== Page load metrics - -The RUM agent tries to capture the overall user experience on how the page is loaded/rendered as part of the page load Transaction. -It includes all of the dependent resources, like JavaScript, stylesheets, images, etc., which are included as part of the page. In addition -to capturing the resource timing information as Spans, the transaction also includes navigation spans—marks that are associated with the rest -of the captured information to make the waterfall more appealing. - -`Domain lookup`:: -Duration of the DNS query for the current page: `domainLookupEnd` - `domainLookupStart`. - -`Making a connection to the server`:: -Duration of the TCP connection to the server, including the TLS negotiation time for HTTPS pages: `connectEnd` - `connectStart`. - -`Requesting and receiving the document`:: -Overall response time of the server including the last byte: `responseEnd` - `requestStart`. - -`Parsing the document, executing sync. scripts`:: -HTML document parsing time, including synchronous Stylesheets and Script: `tagsdomInteractive` - `domLoading`. - -`Fire "DOMContentLoaded" event`:: -Triggered when the browser completes parsing the document. Helpful when there are multiple listeners, or logic -is executed: `domContentLoadedEventEnd` - `domContentLoadedEventStart`. - -`Fire "load" event`:: -Trigged when the browser finishes loading its document and dependent resources: `loadEventEnd` - `loadEventStart`. - -`Time to first byte (TTFB)`:: -Duration from the browser making an HTTP request for the initial document to the first byte of the page being received. TTFB is available from the Navigation Timing API as the `reponseStart` timestamp, and captured as transaction mark `transaction.marks.agent.timeToFirstByte` in the ElasticSearch document. - -To capture the overall user experience of the page including all of the above information plus additional resource requests that might be -triggered during the execution of dependent resources, the `page-load` transaction duration might not always reflect the -https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event[Load] event of the browser and can extend beyond the event. - -If you are interested in accurately measuring the duration of load event, the information can be extracted by using -`Fire load event` Span or from the Transaction marks available as `transaction.marks.agent.domComplete` in the Elasticsearch document. - -NOTE: The page load transaction is measured relative to the `fetchStart` timestamp from the Navigation Timing API. - - -[float] -[[user-centric-metrics]] -=== User-centric Metrics - -To understand the performance characteristics of a web page beyond the page load and how the user perceives performance, the agent supports capturing these https://web.dev/user-centric-performance-metrics/[responsiveness metrics]. - -`First contentful paint (FCP)`:: -Focusses on the initial rendering and measures the time from when the page starts loading to when any part of the page's content is displayed on the screen. The agent uses the https://www.w3.org/TR/paint-timing/#first-contentful-paint[Paint timing API] available in the browser to capture the timing information. FCP is captured as transaction mark for `page-load` transaction for all chromium-based browsers (Chrome >60, Edge >79, Opera >47, etc.). - -`Largest contentful paint (LCP)`:: -A new page-load metric that denotes the time from when the page starts loading to when the critical element (largest text, image, video elements) is displayed on the screen. LCP is available in the browser through -https://wicg.github.io/largest-contentful-paint/[LargestContentfulPaint API] which relies on the draft https://wicg.github.io/element-timing/[Element Timing API]. LCP is one of the https://web.dev/vitals/[core web vitals] metrics and -available only in Chrome >77. Captured as transaction mark for `page-load` transaction, maintain LCP within the first *2.5 seconds* of page-load to provide a good user experience. - -Interaction to next paint (INP):: -INP quantifies responsiveness to user interactions. -The INP value comes from measuring the latency of all click, tap, and keyboard interactions that happen throughout a single page visit and choosing the longest interaction observed. -INP is one of the https://web.dev/vitals/[core web vitals] metrics, -and you can read more about INP in the https://web.dev/articles/inp[web.dev docs]. -To provide a good user experience, Google recommends an INP of *fewer than 200 milliseconds*. - -`First input delay (FID)`:: -FID quantifies the experience of the user when they interact with the page during the page load. It is measured as the time between when a user first interacts with your site (mouse clicks, taps, select dropdowns, etc.) to the time when the -browser can respond to that interaction. FID is one of the https://web.dev/vitals/[core web vitals] metrics and available only in Chrome >85 via https://wicg.github.io/event-timing/[Event Timing API]. FID is captured as `First Input Delay` span for `page-load` transaction. Maintain FID *below 100 milliseconds* to provide a good user experience. - -`Total blocking time (TBT)`:: -The sum of the blocking time (duration above 50 ms) for each long task that occurs between the First contentful paint and the time when the transaction is completed. https://web.dev/tbt/[Total blocking time] is a -great companion metric for https://web.dev/tti/[Time to interactive] (TTI) which is lab metric and not available in the field through browser APIs. The agent captures TBT based on the number of long tasks that occurred during the page load lifecycle. Captured as `Total Blocking Time` span for `page-load` transaction. - -`Cumulative layout shift (CLS)`:: -Metric that represents the cumulative score of all unexpected layout shifts that occur during the entire lifespan of the page. CLS is one of the https://web.dev/vitals/[core web vitals] metrics and here is -https://web.dev/cls/#layout-shift-score[how the score is calculated by Chrome]. Maintain a score of *less than 0.1* to provide a good user experience. - -`Long Tasks`:: -A long task is any user activity or browser task that monopolize the UI thread for extended periods (greater than 50 milliseconds) and block other critical tasks (frame rate or input latency) -from being executed. The agent uses the https://www.w3.org/TR/longtasks/[Long Task API] which is only available in chromium-based browsers (Chrome >58, Edge >79, Opera >69). Captured as `Longtask` span for all managed transactions. -Learn more about <>, and how to interpret them. - -`User Timing`:: -The https://www.w3.org/TR/user-timing/[User Timing] spec exposes API for developers to add custom performance entries to their web application. These custom metrics allow users to measure the hot paths of the app code that helps to identify a good user experience. RUM agent records all of the https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMeasure[performance.measure] calls as spans by their measure name in the waterfall for all managed transactions. - - -[float] -[[user-interactions]] -=== User Interactions - -The RUM agent automatically instruments click event listeners that are -registered by the application. The click events are captured as `user-interaction` -transactions. However, to avoid sending too many `user-interaction` transactions -to the server, the agent discards transactions with no spans (e.g. no network activity). Furthermore, -if the click interaction results in route change, then a `route-change` -transaction would be captured instead. - -The transaction name can be influenced either by using the `name` or preferably the `data-transaction-name` HTML attribute. -Examples of transaction names based on the html attributes present: - -* ``: `Click - button` - -* ``: `Click - button["purchase"]` - -* ``: `Click - purchase` - - -[float] -[[spa]] -=== Single Page Applications - -All history `pushState` events will be captured as transactions. -Most of these transactions can be enhanced by using framework specific integrations. -For all unsupported frameworks/libraries, you can instrument the application -by creating <> and custom spans with the <>. - - -[float] -[[frameworks]] -=== Frameworks - -The agent supports <>. - -To instrument custom metrics, like rendering time or mounting time of components on frameworks like React, Angular, Vue, -etc., use the <>. - -The core RUM agent supports websites based on multi-page (MPA) and single-page architectures (SPA). The core RUM agent can be used on its own with SPA sites, but we recommend using our framework-specific integrations for the following reasons: - -* *Pages are better grouped by routes*: This results in the `transaction.name` field mapping to the actual application route path declared in the SPA application. -* *Exact SPA navigation rendering*: Integration packages hook into the component lifecycle and measure the duration of the SPA transaction correctly. The core RUM agent is unable to determine when an SPA navigation is rendered and instead waits for the last network request before considering the SPA transition is finished. -* *Improved error capturing*: For example, when an error is thrown inside an Angular application, the framework integration will automatically capture it. The core RUM agent, however, is unable to capture the error as the default error handler doesn’t rethrow the error as a browser event. - -[float] -[[platforms]] -=== Platforms - -The following platforms are supported: - -// Update this image by modifying this URL: -// https://badges.herokuapp.com/browsers?android=5.1&firefox=52&googlechrome=49,74&iexplore=11&iphone=12µsoftedge=17&safari=9 -// Additional information: https://github.com/exogen/badge-matrix -image::images/compatibility.png[Elastic APM RUM Agent compatibility] diff --git a/docs/transaction-api.asciidoc b/docs/transaction-api.asciidoc deleted file mode 100644 index 9485e5f25..000000000 --- a/docs/transaction-api.asciidoc +++ /dev/null @@ -1,168 +0,0 @@ -[[transaction-api]] - -=== `Transaction` API - -A transaction groups multiple spans in a logical group. - -To start a transaction, -you need to call <>. - -To see an example of using custom transactions, -see the <> article. - -[float] -[[transaction-name]] -==== `transaction.name` - -* *Type:* String -* *Default:* `Unknown` - -The name of the transaction. - -Can be used to set or overwrite the name of the transaction (visible in the performance monitoring breakdown). - - -[float] -[[transaction-type]] -==== `transaction.type` - -* *Type:* String -* *Default:* `custom` - -The type of the transaction. - - -[float] -[[transaction-timestamp]] -==== `transaction.timestamp` - -* *Type:* String -* *Default:* `undefined` - -The timestamp of the transaction. -If the transaction timestamp is not provided (the default behaviour), it will be set by the apm-server (v6.3+). -You can, however, set the timestamp on the client (using `new Date().toISOString()`), but you should be aware that the timestamp will reflect the client's local time -which might not always be accurate. - - -[float] -[[transaction-start-span]] -==== `transaction.startSpan([name][, type][, options])` - -[source,js] ----- -const span = transaction.startSpan('My custom span') ----- - -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. - -When a span is started it will measure the time until <> is called. Blocked -spans allow users to control the early closing of <> in some cases. - -See also the <> docs for details on how to use custom spans. - -[float] -[[transaction-block]] -==== `transaction.block(flag)` - -[source,js] ----- -transaction.block(true) ----- - -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. - -Most of the time, users shouldn't need to block the running transaction as the agent tries to account for all of the async network activity and capture -the required information. The block API is useful when you think auto instrumented code misses important activity and prematurely ends a transaction. -An example of this might be a page that contains lots of asynchronous tasks that cannot be automatically instrumented, like web workers. - -[source,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) ----- - -One can also achieve a similar action by creating blocked spans. Check the <> guide to learn more. - - -[float] -[[transaction-add-labels]] -==== `transaction.addLabels()` - -[source,js] ----- -transaction.addLabels({ [name]: value }) ----- - -Add several labels on the transaction. If an error happens during the transaction, -it will also get tagged with the same labels. - -Labels are key/value pairs that are indexed by Elasticsearch and therefore searchable (as opposed to data set via <>). - -TIP: Before using custom labels, ensure you understand the different types of -{observability-guide}/apm-api-metadata.html[metadata] that are available. - -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. - -WARNING: Avoid defining too many user-specified tags. -Defining too many unique fields in an index is a condition that can lead to a -{ref}/mapping.html#mapping-limit-settings[mapping explosion]. - -[float] -[[transaction-end]] -==== `transaction.end()` - -[source,js] ----- -transaction.end() ----- - -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. - -[float] -[[transaction-mark]] -==== `transaction.mark(key)` - -[source,js] ----- -transaction.mark(key) ----- - -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. - -Arguments: - -* `key` - Any string. All periods (.), asterisks (*), and double quotation marks (") will be replaced by underscores (_), as those characters have special meaning in Elasticsearch diff --git a/docs/troubleshooting.asciidoc b/docs/troubleshooting.asciidoc deleted file mode 100644 index db87f7e82..000000000 --- a/docs/troubleshooting.asciidoc +++ /dev/null @@ -1,96 +0,0 @@ -[[troubleshooting]] -== Troubleshooting - -[float] -[[errors-originating-from-agent]] -=== Some errors in the application appear to be originating from the agent's JavaScript file -In some cases when you look at the stack trace of an error, it appears to be originating from -the agent's JavaScript file. However, since we need to patch some browser APIs in order to provide -some of the core functionalities of the agent, our JavaScript file appears in the error stack trace. -Often, the error is generated from another part your application, you can follow the stack trace -further to identify the offending code. - - -Of course, there are errors that might have been caused by the agent itself and we appreciate it if -you <>. - -[float] -[[cross-origin-script-error]] -=== Some errors in the application only show `script error` -In some cases when you look at the details of an error, the only information you can see is the message `Script error`. -This happens when an error originates from a JavaScript file served from a different origin than the page's origin. - -In order to get visibility of the error's detail, you must do two things. - -1. Add the attribute `crossorigin` to the `