Uptrace for JavaScript¶
This document describes Uptrace for Web browsers. For Node.js see @uptrace/node.
Installation¶
npm:
npm install @uptrace/web --save-dev
yarn:
yarn add @uptrace/web --dev
Introduction¶
@uptrace/web is the official Uptrace client for JavaScript that sends your traces/spans to Uptrace.
To learn about tracing, please see Introduction to distributed tracing.
Configuring Uptrace client¶
You configure Uptrace client using a DSN (Data Source Name, for example, https://<token>@api.uptrace.dev/<project_id>
) from the project settings page.
import { createClient } from '@uptrace/web'
# Set dsn or UPTRACE_DSN env var.
const dsn = ''
// createClient automatically setups window.onerror handler.
const upclient = createClient({
dsn,
})
The following example shows how to create a tracer, start spans and add events:
const tracer = upclient.getTracer('github.com/uptrace/uptrace-js')
// Report an exception.
upclient.reportException(new Error('hello world'), {
foo: 'bar',
})
// Start a root/main span (span without a parent).
const mainSpan = tracer.startSpan('main span')
// Activate main span.
tracer.withSpan(mainSpan, () => {
// span1 is a child of mainSpan.
const span1 = tracer.startSpan('span1', {
parent: tracer.getCurrentSpan(),
})
// Activate span1.
tracer.withSpan(span1, () => {
const span = tracer.getCurrentSpan() // == span1
span.setAttribute('key1', 'value1')
span.addEvent('event-name')
span.end()
})
// span2 is a child of mainSpan.
const span2 = tracer.startSpan('span2', {
parent: tracer.getCurrentSpan(),
})
// Activate span2.
tracer.withSpan(span2, () => {
const span = tracer.getCurrentSpan() // == span2
span.setAttribute('key2', 'value2')
span.addEvent('event-name')
span.end()
})
const span = tracer.getCurrentSpan() // == mainSpan
span.end()
})
Instrumenting your code¶
To report exceptions directly (without a span):
upclient.reportException(new Error('hello world'), {
key1: 'value1',
key2: 'value2',
})
To create a tracer:
const tracer = upclient.getTracer('github.com/my/repo')
To create a span:
// Main/root span.
const span = tracer.startSpan('span-name')
// Span with a parent.
const span2 = tracer.startSpan('span2', {
parent: span,
})
To get the active span:
const span = tracer.getCurrentSpan()
To activate the span:
tracer.withSpan(span, () => {
console.log(tracer.getCurrentSpan() === span)
})
To set an attribute:
// Single attribute.
span.setAttribute('key1', 'value1')
// Multiple attributes.
span.setAttributes({
key1: 'value1',
key2: 'value2',
})
To record an exception:
span.recordException(new Error('hello world'))
To add an event:
span.addEvent('event-name', {
key1: 'value1',
key2: 'value2',
})
Instrumenting Vue.js 2.x¶
import Vue from 'vue'
const dsn = 'https://<token>@api.uptrace.dev/<project_id>'
const upclient = createClient({
dsn,
})
Vue.config.errorHandler = (err, vm, info) => {
upclient.reportException(err, {
vm: vm,
info: info,
})
}