Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@sumologic/opentelemetry-rum

SumoLogic35.9kApache-2.04.6.2TypeScript support: included

Adds OpenTelemetry tracing auto-instrumentation in the browser. Collects spans on network events and sends them to Sumo Logic.

opentelemetry, tracing, sumologic, sumo, rum, ot

readme

Sumo Logic OpenTelemetry RUM

The Sumo Logic OpenTelemetry auto-instrumentation for JavaScript library enables tracing in the browser.

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
  • 103 KB (31 KB gzipped)

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://rum.sumologic.com/sumologic-rum.js"
  type="text/javascript"
></script>
<script>
  window.sumoLogicOpenTelemetryRum &&
    window.sumoLogicOpenTelemetryRum.initialize({
      collectionSourceUrl: 'sumo_logic_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,
    'sumoLogicOpenTelemetryRum',
    document,
    'https://rum.sumologic.com/sumologic-rum.js',
  );
  window.sumoLogicOpenTelemetryRum.onReady(function () {
    window.sumoLogicOpenTelemetryRum.initialize({
      collectionSourceUrl: 'sumo_logic_traces_collector_source_url',
      serviceName: 'name_of_your_web_service',
      propagateTraceHeaderCorsUrls: [
        'list_of_domains_to_receive_trace_context',
      ],
      collectErrors: true,
    });
  });
</script>

Note: XHR and navigation/route changes support as well as errors collection requires RUM script in version 4 or higher (https://rum.sumologic.com/sumologic-rum-v4.js). Please ensure you are using the correct version in your pages. For automatic updates use https://rum.sumologic.com/sumologic-rum.js.

Note: Above examples omit the version of the script in the src attribute and automatically uses most up to date version of it. If you want to manually control versioning of the script please use:

Manual installation

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

Inside your project directory execute npm install @sumologic/opentelemetry-rum.

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

import { initialize } from '@sumologic/opentelemetry-rum';

initialize({
  collectionSourceUrl: 'sumo_logic_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:

Parameter Type Default Description
collectionSourceUrl string required Sumo Logic collector source url
authorizationToken string | Sumo Logic collector authorization token
serviceName string "unknown" Name of your web service
applicationName string | Name of your application
deploymentEnvironment string | The software deployment (e.g. staging, production)
defaultAttributes object {} Attributes added to each span
samplingProbability number 1 1 means all traces are sent, 0 - no traces are send, 0.5 - there is 50% change for a trace to be sent
bufferMaxSpans number 2048 Maximum number of spans waiting to be send
maxExportBatchSize number 50 Maximum number of spans in one request
bufferTimeout number 2000ms Time 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
collectSessionId boolean true Enables collecting rum.session_id attribute
dropSingleUserInteractionTraces boolean true Automatically drops traces with only one span coming from the user-interaction instrumentation (click etc.)
collectErrors boolean true Automatically collect and send uncaught exceptions, unhandled rejections, document errors and console errors
userInteractionElementNameLimit number 20 Limit for user interaction element name, after which the name will be truncated with ... suffix.
getOverriddenServiceName (span: Span) => string | Function 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.sumologic.com or http://localhost:3000/api URLs
propagateTraceHeaderCorsUrls: [
  /^https:\/\/api\.sumologic.com\/.*/,
  /^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.sumoLogicOpenTelemetryRum pulled from OpenTelemetry upstream:

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

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

Useful links:

Manual instrumentation

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

Example:

const { tracer, api, recordError } = sumoLogicOpenTelemetryRum;
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 sumoLogicOpenTelemetryRum 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.

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

Public API

All method are available under the window.sumoLogicOpenTelemetryRum object.

setDefaultAttribute(key, value)

Extends the list of default attributes specified during initialization.

Example: window.sumoLogicOpenTelemetryRum.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.sumoLogicOpenTelemetryRum.getCurrentSessionId()

recordError()

Sends an error with the given message and optional attributes.

Example: window.sumoLogicOpenTelemetryRum.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.

changelog

CHANGELOG

4.6.2

  • fix xhr metrics issue for XMLHttpRequest

4.6.1

  • added support to ignore URLs from being instrumented

4.6.0

  • updated logs proto 0.9 -> 0.19

4.5.0

  • updated OT-JS to API 1.8.0 / Core 1.22.0 / Experimental 0.49.0

4.4.0

4.3.0

  • updated OT-JS to 0.35.0

4.2.1

  • fixed longtask http.action_type classification
  • fixed missing root span operation for some longtask spans

4.2.0

  • new property in the initialize function: getOverriddenServiceName, which allows to override the service name of a span during its creation

4.1.1

  • fixed patching addEventListener in instrumentation-user-interaction

4.1.0

  • added userInteractionElementNameLimit initialization option
  • fixed handling navigation event

4.0.0

  • support for collecting uncaught exceptions, unhandled rejections, document errors and console errors
  • new properties in the initialize function: deploymentEnvironment and collectErrors
  • fixed document.visibilityState for pages open in background

3.1.0

  • extended document.visbilityState discoverability for root spans
  • fixed broken span timings on some browsers
  • XHR & longtask metrics

3.0.0

  • updated @opentelemetry/api to 1.1.0 - breaking changes
  • updated opentelemetry-js to 1.0.1
  • updated opentelemetry-js-contrib to 935149c
  • added sumologic.rum.version default attribute
  • added sumoLogicOpenTelemetryRum.getCurrentSessionId()
  • added attribute new.location.href to Navigation: * spans

Check "Manual instrumentation" in README for new instructions.

2.1.1

  • fixed 'Error: timeout' logs

2.1.0

  • reduced size to 88 KB (26 KB gzipped)
  • support for more user interactions like dblclick, submit, drop etc.
  • full History API and hash change support
  • web-vitals
  • session id (can be disabled using the collectSessionId option)
  • longtasks with automatic context attaching
  • added 'setDefaultAttribute' method
  • added 'maxExportBatchSize' configuration option and changed default values of current exporter-related configuration
  • automatic removing of single user interaction traces (can be disabled using the dropSingleUserInteractionTraces option)
  • new context manager with better support for native async-await, observers and more
  • new attribute 'document.visibilityState' and span events 'pageshow' and 'pagehide'

2.0.1

  • samplingProbability property in the initialize function's options argument can be a string.

2.0.0

  • renamed package to @sumologic/opentelemetry-rum
  • renamed global variable to sumoLogicOpenTelemetryRum
  • changed the way script can be configured
  • updated OT-JS to 0.24.0

1.4.4

  • fixed doubled instrumentation-document-load traces when the script is loading asynchronously

1.4.3

  • fixed manual installation

1.4.1

  • fixed manual installation

1.4.0

  • added registerInstrumentations() and disableInstrumentations() methods to turn on and off instrumentations in runtime

1.3.0

  • added http.url and http.user_agent attributes to the documentFetch spans
  • fixed propagating trace header cors to all domains by default

1.2.0

  • added sampling.probability default attribute
  • added support for manual instrumentation
  • added first paint, first contentful paint and largest contentful paint events to documentLoad

1.1.0

1.0.0

0.2.0

  • added sumologic.telemetry.sdk.export_timestamp tag with a timestamp of spans being exported (#5)

0.1.0