OpenTelemetry Events in JavaScript

The finest-grained tracing tool is the event system.

Span events are a form of structured logging. Each event has a name, a timestamp, and a set of attributes. When events are added to a span, they inherit the span's context. This additional context allows events to be searched, filtered, and grouped by trace ID and other span attributes.

Span context is one of the key differences between distributed tracing and traditional logging.

Adding events

Events are automatically timestamped when they are added to a span. Timestamps can also be set manually if the events are being added after the fact.

For example, enqueuing an item might be recorded as an event.

// Get the current span
const span = tracer.getCurrentSpan();

// Perform the action

// Record the action
span.addEvent( “enqueued item“, {
  "", myItem.ID(),
	"": queue.ID(),
	"queue.length": queue.length(),

Spans should be created for recording course-grained operations, and events should be created for recording fine-grained operations.

Recording exceptions

Many of the tracing conventions can apply to event attributes as well as span attributes. The most important event-specific convention is recording exceptions.

const span = trace.getCurrentSpan();

// recordException converts the error into a span event. 

// If the exception means the operation results in an 
// error state, you can also use it to update the span status.
span.span.setStatus({ code: CanonicalCode.INTERNAL });

Marking the span as an error is independent from recordings exceptions. To mark the entire span as an error, and have it count against error rates, set the SpanStatus to any value other than OK.

StatusCode definitions can be found in the OpenTelemetry specification. If no status code directly maps to the type of error you are recording, set the status code to UNKOWN for common errors, and INTERNAL for serious errors.