OpenTelemetry Events in Go
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.
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.
import "go.opentelemetry.io/otel/label" // Get the span span := tracer.SpanFromContext(ctx) // Perform the action queue.Enqueue(myItem) // Record the action span.AddEvent(ctx, "enqueued item", label.String("key1", "value1")) label.String("item.id", myItem.ID()), label.String("queue.id": queue.ID()), label.String("queue.length": queue.Length()), })
Spans should be created for recording course-grained operations, and events should be created for recording fine-grained operations.
Many of the tracing conventions can apply to event attributes as well as span attributes. The most important event-specific convention is recording exceptions.
import "go.opentelemetry.io/otel/codes" span := tracer.SpanFromContext(ctx) // RecordError converts an error into a span event. span.RecordError(ctx, err) // If the error indicates that the entire operation is an // errored state, update the span status. span.SetStatus(codes.Internal, "critical error")
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.