0.1.12 • Published 4 months ago

@vunet/otel-rum v0.1.12

Weekly downloads
-
License
Apache-2.0
Repository
-
Last release
4 months ago

Vunet OTEL RUM

The Vunet RUM OTEL auto-instrumentation JavaScript library is designed to enhance your browser experience by enabling both Session Replay and tracing. This powerful tool allows developers to capture and replay user sessions, providing valuable insights into user interactions and behaviors. Additionally, it facilitates comprehensive tracing within the browser, helping to identify and diagnose performance issues and errors more effectively.

Features

  • XMLHttpRequest and Fetch APIs auto-instrumentation
  • user interactions like click, submit, drop etc.
  • document load with fetched resources
  • History API and hash change support
  • web-vitals
  • session id
  • longtasks with automatic context attaching
  • uncaught exceptions, unhandled rejections, document errors and console errors
  • support for manual instrumentation
  • automatic context carrying through timers, promises, native async-await, events, observers and more

Installation

The easiest way to start collecting traces from your website is to put the code below inside the <head></head> tags on your website:

<script
  src="https://cdn.vunet.io/otel-rum/latest/rum.js"
  type="text/javascript"
></script>
<script>
  window.vunetRum &&
    window.vunetRum.initialize({
      collectionSourceUrl: 'vunet_traces_collector_source_url',
      serviceName: 'name_of_your_web_service',
      propagateTraceHeaderCorsUrls: [
        'list_of_domains_to_receive_trace_context',
      ],
      collectErrors: true,
    });
</script>

See configuration for all supported options.

There are no other required actions needed to take. With properly provided collectionSourceUrl and serviceName your website is ready and will send collected traces to the specified Sumo Logic collector.

You can load the script asynchronously using the script below, but some functionalities like user interactions or requests made before script run will be limited.

<script>
  (function (w, s, d, r, e, n) {
    (w[s] = w[s] || {
      readyListeners: [],
      onReady: function (e) {
        w[s].readyListeners.push(e);
      },
    }),
      ((e = d.createElement('script')).async = 1),
      (e.src = r),
      (n = d.getElementsByTagName('script')[0]).parentNode.insertBefore(e, n);
  })(
    window,
    'vunetRum',
    document,
    'https://cdn.vunet.io/otel-rum/latest/rum.js',
  );
  window.vunetRum.onReady(function () {
    window.vunetRum.initialize({
      collectionSourceUrl: 'vunet_traces_collector_source_url',
      serviceName: 'name_of_your_web_service',
      propagateTraceHeaderCorsUrls: [
        'list_of_domains_to_receive_trace_context',
      ],
      collectErrors: true,
    });
  });
</script>

Manual installation

The other option is to bundle this library inside your project and initialize it.

Inside your project directory execute npm install @vunet/otel-rum.

RUM needs to be initialized preferably before other functionalities in your code:

import { initialize } from '@vunet/otel-rum';

initialize({
  collectionSourceUrl: 'vunet_traces_collector_source_url',
  serviceName: 'name_of_your_web_service',
  propagateTraceHeaderCorsUrls: ['list_of_domains_to_receive_trace_context'],
});

Configuration

Both script tag and manual installation can be configured with following parameters:

ParameterTypeDefaultDescription
collectionSourceUrlstringrequiredSumo Logic collector source url
authorizationTokenstringSumo Logic collector authorization token
serviceNamestring"unknown"Name of your web service
applicationNamestringName of your application
deploymentEnvironmentstringThe software deployment (e.g. staging, production)
defaultAttributesobject{}Attributes added to each span
samplingProbabilitynumber11 means all traces are sent, 0 - no traces are send, 0.5 - there is 50% change for a trace to be sent
bufferMaxSpansnumber2048Maximum number of spans waiting to be send
maxExportBatchSizenumber50Maximum number of spans in one request
bufferTimeoutnumber2000msTime in milliseconds for spans waiting to be send
ignoreUrls(string\|RegExp)[][]List of XHR URLs to ignore (e.g. analytics)
propagateTraceHeaderCorsUrls(string\|RegExp)[][]List of URLs where W3C Trace Context HTTP header will be injected
collectSessionIdbooleantrueEnables collecting rum.session_id attribute
dropSingleUserInteractionTracesbooleantrueAutomatically drops traces with only one span coming from the user-interaction instrumentation (click etc.)
collectErrorsbooleantrueAutomatically collect and send uncaught exceptions, unhandled rejections, document errors and console errors
userInteractionElementNameLimitnumber20Limit for user interaction element name, after which the name will be truncated with ... suffix.
getOverriddenServiceName(span: Span) => stringFunction used for overridding the service name of a span during its creation.

Trace context propagation

By default, trace context propagation, allowing creation of end to and front end to backend traces for cross-origin requests is not enabled because of browser CORS security restrictions. To propagate tracing context to create front-end to back-end traces, set exact URLs or URL patterns in the propagateTraceHeaderCorsUrls configuration option. You must configure your server to return accept and return following CORS headers in its response: Access-Control-Allow-Headers: traceparent, tracestate. Read W3C Trace Context for more details. Sumo Logic cannot perform any validation correct configuration of services of other origins, so, please be careful when configuring this. You should always try enabling CORS in a test environment before setting it up in production.

For example:

// propagates trace context in requests made to https://api.vunet.io or http://localhost:3000/api URLs
propagateTraceHeaderCorsUrls: [
  /^https:\/\/api\.vunet.io\/.*/,
  /^http:\/\/localhost:3000\/api\/.*/,
],

Baggage

Baggage is contextual information that’s passed between spans. It’s a key-value store that resides alongside span context in a trace, making values available to any span created within that trace.

Imagine you want to have a customerId attribute on every span in your trace, which involves multiple services; however, customerId is only available in one specific service. To accomplish your goal, you can use OpenTelemetry Baggage to propagate this value across your system. In that sense it is different than defaultAttributes, which does not allow for data to be added dynamically. It could be said that setDefaultAttribute() serves similar function as Baggage (as attributes can be defined dynamically); however it will not add attributes retroactively (spans sent before calling setDefaultAttribute()).

OpenTelemetry uses Context Propagation to pass Baggage around, and each of the different library implementations has propagators that parse and make that Baggage available without you needing to explicitly implement it.

Baggage can be used by accessing methods in our window.vunetRum pulled from OpenTelemetry upstream:

const baggage =
  window.vunetRum.api.propagation.getBaggage(
    window.vunetRum.api.context.active(),
  ) || window.vunetRum.api.propagation.createBaggage();

baggage.setEntry('customerId', { value: 'customer-id-value' });
window.vunetRum.api.propagation.setBaggage(
  window.vunetRum.api.context.active(),
  baggage,
);

Useful links:

Manual instrumentation

When initialized by the <script /> tag, window attribute vunetRum is exposed. It gives possibility to create spans manually. Global vunetRum objects contains:

Example:

const { tracer, api, recordError } = vunetRum;
const span = tracer.startSpan('fetchUserData', {
  attributes: { organization: 'client-a' },
});
api.context.with(api.trace.setSpan(api.context.active(), span), () => {
  // long running operation
});
recordError('Cannot load data', { organization: 'test' });

Using in production, make sure your website works when vunetRum is not defined (e.g. blocked by a browser extension).

Disable instrumentation

Instrumentation can be disabled and enabled again in runtime using registerInstrumentations() and disableInstrumentations() methods.

vunetRum.disableInstrumentations();
// some code with instrumentations disabled
vunetRum.registerInstrumentations();

Public API

All method are available under the window.vunetRum object.

setDefaultAttribute(key, value)

Extends the list of default attributes specified during initialization.

Example: window.vunetRum.setDefaultAttribute('user_id', userId)

getCurrentSessionId()

Returns current value of the rum.session_id attribute. Returned value may change in time, so don't cache it.

Example: window.vunetRum.getCurrentSessionId()

recordError()

Sends an error with the given message and optional attributes.

Example: window.vunetRum.recordError('Cannot load data', { organization: 'test' })

License

This project is released under the Apache 2.0 License.

Contributing

Please refer to our Contributing documentation to get started.

Code Of Conduct

Please refer to our Code of Conduct.

0.1.11

4 months ago

0.1.12

4 months ago

0.1.10

5 months ago

0.1.9

5 months ago

0.1.8

6 months ago

0.1.7

6 months ago

0.1.6

6 months ago

0.1.5

6 months ago

0.1.4

6 months ago

0.1.3

6 months ago

0.1.2

6 months ago

0.1.1

6 months ago

4.6.1

6 months ago