Sub topic 3
Attributes, events and status on a span
This chapter assumes you have read the previous chapter on traces and spans. You should know that a span has a name, a start time, an end time and a parent. You should also be comfortable with Python context managers. Here you will learn the three ways a span carries information beyond timing: attributes, events and status.
Attributes: facts about the whole span
An attribute is a key-value pair attached to a span. It describes something that is true of the operation as a whole, such as the model name, the number of retrieved documents, or the customer tier. Keys are strings. Values must be one of these:
- A string, boolean, integer or float.
- A list of values of one of those types. All items in a list must share the same type.
None, dictionaries and mixed lists are not valid values. The Python SDK logs a warning and drops them, so the attribute silently goes missing from your trace.
You can set attributes in three ways.
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support_agent")
def classify(ticket: str) -> str:
with tracer.start_as_current_span(
"classify ticket", attributes={"app.ticket.channel": "email"}
) as span:
span.set_attribute("app.ticket.length", len(ticket))
span.set_attributes(
{"app.ticket.language": "en", "app.ticket.flags": ["refund", "urgent"]}
)
span.add_event("cache.miss", {"app.cache.key_hash": "ab12"})
label = "refund" if "refund" in ticket else "other"
span.set_attribute("app.ticket.label", label)
return label
print(classify("I want a refund for order A-1001"))Run this and the console exporter prints the finished span as JSON. You will see the four attribute sources merged into one attributes object and the event listed separately.
Set attributes at creation when you can
Passing attributes= to start_as_current_span is more than a convenience. A sampler decides whether to record a span at the moment the span starts. It sees only the attributes supplied at creation. If you want to sample on app.ticket.channel, set it in the constructor, not afterward.
Naming and cardinality
Use dotted, lowercase names. For GenAI data, use the gen_ai.* names from the semantic conventions, which a later chapter covers. For your own data, use a prefix you own, such as app.. Do not reuse a standard namespace for a custom meaning.
Cardinality matters because most backends index attributes. A value such as app.ticket.label has a handful of possibilities. A value such as a full prompt or a request ID has millions. High-cardinality attributes are fine on spans, but they are a problem if you later copy them onto metrics.
Limits
Attributes are not free. The SDK enforces limits that you can tune with environment variables:
| Variable | Default | Effect when exceeded |
|---|---|---|
| `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT` | 128 | Extra attributes are dropped |
| `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` | unlimited | Longer strings are truncated if set |
| `OTEL_SPAN_EVENT_COUNT_LIMIT` | 128 | Extra events are dropped |
Setting the same key twice overwrites the earlier value. The last write wins.
Events: things that happened at a moment
An event is a named, timestamped record inside a span. It can carry its own attributes. Use an event when the time within the span matters, or when something can happen more than once.
Compare two cases from an agent run:
- The model finished with
stopas its finish reason. That is a single fact about the span, so it is an attribute. - The call hit a rate limit, waited, and tried again twice. That is a sequence of moments, so each retry is an event.
import time
from opentelemetry import trace
tracer = trace.get_tracer("support_agent")
def call_with_retries(send, attempts: int = 3):
with tracer.start_as_current_span("chat example-model") as span:
for attempt in range(1, attempts + 1):
try:
return send()
except TimeoutError:
span.add_event("retry", {"app.retry.attempt": attempt})
time.sleep(0.1 * attempt)
raise TimeoutError("model did not answer")add_event(name, attributes=None, timestamp=None) uses the current time by default. The optional timestamp is in nanoseconds since the Unix epoch, which helps when you report something that happened earlier.
Events add to the size of every span that carries them. A loop that emits an event per streamed token will hit the event limit and inflate your storage. If you need that detail, aggregate it into a count attribute.
The exception event
span.record_exception(exc) adds an event named exception with the attributes exception.type, exception.message and exception.stacktrace. It does not change the span's status. Recording an exception and marking a span as failed are two separate steps.
Status: did the operation succeed
Every span has a status with one of three codes.
| Code | Meaning | Who should set it |
|---|---|---|
| `UNSET` | Default. No judgment was made. | Nobody. Leave it for success. |
| `ERROR` | The operation failed. Accepts a description. | Your code or the instrumentation |
| `OK` | The application explicitly confirms success. | Your code, rarely |
The SDK applies these rules:
- A description is kept only with
ERROR. ERRORcan be overwritten byOK.OKis final. Laterset_statuscalls are ignored.- Setting
UNSEThas no effect.
Most successful spans should end as UNSET. Backends treat UNSET as "no error". Marking every span OK removes your ability to tell "confirmed good" apart from "nobody checked".
Failures that do not raise exceptions
LLM apps often fail without throwing. The model returns text, but the JSON is invalid, a guardrail rejects the output, or the loop hit its step limit. The span would stay UNSET unless you say otherwise.
import json
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
tracer = trace.get_tracer("support_agent")
def parse_reply(raw: str) -> dict | None:
with tracer.start_as_current_span("validate reply") as span:
try:
return json.loads(raw)
except json.JSONDecodeError as exc:
span.set_attribute("app.validation.error", "invalid_json")
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, "model returned invalid JSON"))
return NoneHere the function handles the error and returns normally, so the context manager sees no exception. The explicit set_status call is what makes this failure visible.
Common errors
- Double-recording exceptions.
start_as_current_spanhasrecord_exception=Trueandset_status_on_exception=Trueby default. An exception that escapes thewithblock is recorded and marks the spanERRORon its own. If you also callrecord_exceptionand re-raise, as in the earlier model-call example, you get twoexceptionevents. Choose one approach. Manual handling is useful when you want a custom description or want to catch and continue. - Putting an error message in a status description for success. The description is ignored unless the code is
ERROR. - Passing
Noneor a dict. The attribute is dropped with a warning. Convert values first, for examplejson.dumpsfor a dict, or skip the call when the value is missing. - Using events for what should be attributes. If a fact is true once per span, an attribute is cheaper to store and query.
- Setting
OKtoo early. BecauseOKis final, a later real failure cannot change it.
Exercise
A tool call returns an HTTP 200 response whose body says {"error": "customer not found"}, and your code handles it without raising. Which span fields should you set so the failure is visible in a trace backend, and should you set the status to OK on the other spans in the run that succeeded?
Show answer
On the tool span, call setstatus(Status(StatusCode.ERROR, "customer not found")). Optionally add an attribute such as app.tool.errortype and an event or record_exception if you have an exception object. The attribute and event give detail, but only the status marks the span as failed. Leave the successful spans as UNSET. Setting OK is unnecessary and would make later changes impossible.