Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

https://github.com/census-instrumentation/opencensus-web

A stats collection and distributed tracing framework
https://github.com/census-instrumentation/opencensus-web

cloud distributed-tracing end-user-monitoring instrumentation metrics monitoring opencensus real-user-monitoring stats trace tracing

Last synced: 3 months ago
JSON representation

A stats collection and distributed tracing framework

Lists

README

        

> **Warning**
>
> OpenCensus and OpenTracing have merged to form [OpenTelemetry](https://opentelemetry.io), which serves as the next major version of OpenCensus and OpenTracing.
>
> OpenTelemetry has now reached feature parity with OpenCensus, with tracing and metrics SDKs available in .NET, Golang, Java, NodeJS, and Python. **All OpenCensus Github repositories, except [census-instrumentation/opencensus-python](https://github.com/census-instrumentation/opencensus-python), will be archived on July 31st, 2023**. We encourage users to migrate to OpenTelemetry by this date.
>
> To help you gradually migrate your instrumentation to OpenTelemetry, bridges are available in Java, Go, Python, and JS. [**Read the full blog post to learn more**](https://opentelemetry.io/blog/2023/sunsetting-opencensus/).

# OpenCensus - A stats collection and distributed tracing framework
[![Gitter chat][gitter-image]][gitter-url]
[![NPM Published Version][npm-img]][npm-url]
[![circleci][circleci-image]][circleci-url]
[![codecov][codecov-image]][codecov-url]
[![Known Vulnerabilities][snyk-image]][snyk-url]
[![Apache License][license-image]][license-url]

OpenCensus Web is an implementation of [OpenCensus][opencensus-url], a toolkit for collecting
application performance and behavior monitoring data.
This library instruments browser applications to collect user-side performance data.

The library is in alpha stage and the API is subject to change.

Please join [gitter][gitter-url] for help or feedback on this project.

## Overview

OpenCensus Web instruments web applications generates traces for the initial page load of a site
in the browser and the subsequent on-page user interactions after the initial load. Some features
that also provides are automatic tracing for *clicks* and *route transitions*, *custom spans*, and browser
[Resource Timing API][resource-timing-url] data.

It supports sending the trace sampling decision and trace ID from the web server to the
browser client to enable latency debugging across the stack.

## Architecture

OpenCensus Web interacts with three application components:

- *Frontend web server*: renders the initial HTML to the browser including the OpenCensus Web library code
and the necessary configuration (e.g. window.ocAgent). This server would typically be instrumented with an
OpenCensus server-side library (Go, Java, etc.) that can attach the server-side spans to the trace,
that is sending the Trace Context Header in the [W3C draft format][trace-context-url] via a `window.traceparent`
global variable.
We also suggest that you create an endpoint in the server that receives the HTTP/JSON traces and proxies
to the OpenCensus Agent.

- *Browser JS*: the OpenCensus Web library code that runs in the browser. This measures user interactions and
collects browser data and writes them to the OpenCensus Agent as spans via HTTP/JSON.

- *OpenCensus Agent*: receives traces from either the *frontend web server proxy endpoint* or directly from
the *browser JS*, depending on the way you deploy it, and exports them to a trace backend (e.g. Stackdriver, Zipkin).

![architecture-diagram](images/architecture_diagram.png)

## Features

### Trace spans for initial load including server side HTML rendering

Here's a sample trace from OpenCensus Web that was exported to
[Zipkin][zipkin-url]. Notice that there is an overall `nav./` span for the user
navigation experience until the browser `load` event fires. There are also
`/` spans for the client and server side measurements of the initial HTML load.
The server side spans also indicates how much time was spent parsing and
rendering the template:

![zipkin-waterfall](images/zipkin_waterfall.png)

These spans are generated via the browser's
[Navigation Timing][navigation-timing-url] and
[Resource Timing][resource-timing-url] APIs. Notice also the `long js task`
span, which indicates a CPU-bound JavaScript event loop that took more than 50ms
as measured by the [Long Tasks][long-tasks-url] browser API.

### Span annotations for DOM and network events

The OpenCensus Web spans also include detailed annotations for DOM load events
like `domInteractive` and `first-paint`, as well as network events like
`domainLookupStart` and `secureConnectionStart`. Here is a similar trace
exported to [Stackdriver Trace][stackdriver-trace-url] with the annotations
expanded:

![stackdriver-trace-events](images/stackdriver_trace_events.png)

These annotations also comine from the
[Resource Timing API][resource-timing-url]. Note that for resources fetched via
CORS, you will need to specify the
[Timing-Allow-Origin header][timing-allow-origin-url].

### Automatic tracing for click events
OpenCensus Web automatically traces all the *click events* as long as the click is done in a DOM element
(e.g. button) and it is not *disabled*. When the user clicks an element, an interaction is started to
measure all the synchronous and asynchronous code that this interaction may trigger, like network calls or
JS code execution.

OC Web provides the option of adding the attribute `data-ocweb-id` to HTML elements and give a custom name
to the interaction. For the next example, the resulting name will be *‘Save edit user info’*:

```html
Save changes
```

In case you don’t add this attribute, OC web will use the *DOM element ID*, the *tag name* plus the *event name*
involved in the interaction to generate a CSS selector name. For example, clicking this button:

```html
Save changes
```
would generate a span named: *'button#save_changes click'*.

### Automatic tracing for route transitions
OC Web traces route transitions between the different sections of your page by monkey-patching the
[History API][history-api-url]. OC Web names this kind of interaction as ‘Navigation /path/to/page’.
The following trace exported to Stackdriver Trace shows a span named *Navigation /second_page* which
involves some network calls before the route transition is complete:

![navigation-trace-image](images/navigation_trace.png)

### Create your own spans
Instrument your web application with custom spans for tasks or code involved in a user interaction.
Here is a code snippet in JavaScript that shows how to do this with the npm package dependency:

```javascript
import { tracing } from '@opencensus/web-instrumentation-zone';

function handleClick() {
// Start child span which will be child of the current root span on the current interaction.
// To make sure the span is attached to the root span, add this in code that the button is running.
const childSpan = tracing.tracer.startChildSpan({
name: 'name of your child span'
});
// Do some operation...
// Finish the child span at the end of it's operation
childSpan.end();
}

// Create a fake button to point out the custom span is created in the click handler.
const button = document.createElement('button');
button.onclick = handleClick;
```

### Automatic spans for HTTP requests and Browser performance data.
OC Web intercepts HTTP requests generated by an interaction (specifically `XMLHttpRequest` objects)
to automatically create a span for this HTTP request and measure it. Additionally, OC Web sends along
the HTTP request a Trace Context Header in the [W3C Trace Context][trace-context-url] format to the server
as long as the URL is the same origin or matches a provided regex. To provide this *Regex*,
add the `ocTraceHeaderHostRegex` global variable.

In case the server is instrumented with OpenCensus, you can see attached the spans coming from the server
and be able to know the server performance as well. This lets you know if the issues are related to either
the front-end or the server-side.

OC Web also includes [Performance Resource Timing API][resource-timing-url] data to make annotations like
`domainLookupStart` and `responseEnd`, also, generates spans for any [CORS preflight][cors-preflight-url] requests.

The next screenshot shows a trace exported to Stackdriver Trace. Notice the several network calls with the automatic
generated spans (e.g. *‘Sent./sleep’*) with the respective annotations. Also, there are server-side
spans (e.g. *‘/sleep’* and *‘ocweb.handlerequest’*) and *CORS Preflight* related spans.

![automatic-spans-http](images/http_request_spans.png)

### Relate user interactions back to the initial page load tracing.
OC Web attaches the *initial page load trace id* to the user interactions as an *attribute* and a *span link*.
This enables search by attribute to find the *initial load trace* and the interaction traces happening after
the initial load via a single attribute query.

The next screenshot from Stackdriver Trace shows a search by `initial_load_trace_id` attribute containing all
user interaction traces after the initial page loaded.

![all-traces](images/relate_initial_with_interactions.png)

### Export traces to Zipkin, Jaeger, Stackdriver, DataDog, Honeycomb and more

The OpenCensus Web library exports traces via the
[OpenCensus Agent][oc-agent-url], which can then export them to a variety of
trace backends. See the
[OpenCensus Agent/Collector exporter docs][oc-agent-exporter-url] for details.

## Usage

Below are the steps that are currently needed to use it.

### 1. Deploy the OpenCensus agent to collect traces

The OpenCensus Web library currently only exports traces via the
[OpenCensus Agent][oc-agent-url], which can then export them to a trace backend
(e.g. Zipkin, Stackdriver). See this [example's README][initial-load-example-url]
for steps to run the agent locally or in the cloud.

When you run the agent in the cloud you will need to expose it to your
application via the internet. You may also to proxy the agent behind the
authentication or CSRF protection layer of your application to to only allow
traces to be written by authenticated end users.

### 2. Use the OpenCensus Web library code in your application

OpenCensus Web gives tree ways to use it in your application, where you can either
only import the code for the *initial page load* tracing or the whole OpenCensus Web tracing
including the *initial page load* and *user interaction tracing*.

See the [examples/initial_load][examples-initial-load-url] folder for a full
example of how to use *initial page load* functionality in your application. Also, see the
[examples/user_interaction][examples-user-interaction-url] folder for a full
example of how to also trace the user interactions.

#### Using via a `` tag

You can use OpenCensus Web via a `<script>` tag that makes uses of the
<unpkg.com> CDN that serves files from NPM packages.

The script tag should go before the `</body>`. You will also need to set the
`ocAgent` endpoint in a different `<script>` and may also specify the
trace sample rate via an `ocSampleRate` global variable as well.

- If you only want to use the **initial page load** functionality:
```html
...
<script>
// HTTP endpoint of the OpenCensus Agent you ran and exposed to the internet
// in Step 1 above.
ocAgent = 'https://example.com/my-opencensus-agent-endpoint';

// Sample all requests for trace, which is useful when testing.
// By default this is set to sample 1/10000 requests.
ocSampleRate = 1.0;