PRACTICAL GUIDE / Selenium Grid OpenTelemetry tracing
Correlate Selenium Grid Sessions with OpenTelemetry Traces
Correlate Selenium Grid OpenTelemetry traces with WebDriver session IDs, structured events, test artifacts, exporter health, and precise failure boundaries.
In this guide11 sections
- Follow one request across Grid components
- Enable tracing and structured events together
- Put a collector between Grid and the backend
- Capture the session identity in the test harness
- Search event attributes by session.id
- Build a one-to-many correlation record
- Distinguish creation, command, and teardown failures
- Control cardinality, retention, and sensitive data
- Diagnose missing correlation systematically
- Trace correlation checklist
- End every failure with a route to evidence
What you will learn
- Follow one request across Grid components
- Enable tracing and structured events together
- Put a collector between Grid and the backend
- Capture the session identity in the test harness
Selenium Grid OpenTelemetry tracing explains how a request moved through distributed Grid components. The test report explains which scenario and WebDriver session failed. Correlation joins those views by recording the session id at the client and searching trace events or structured logs that carry the session.id attribute.
The crucial semantic rule is that session id and trace id are different identifiers. One browser session receives many WebDriver HTTP commands, and each request can have its own trace. Correlation is therefore usually one session to several traces, with the new-session trace, failing command trace, and delete-session trace serving different diagnostic purposes.
Follow one request across Grid components
The official Selenium Grid observability guide states that Selenium Server is instrumented with OpenTelemetry and models a request as a trace containing spans and events. A new-session path can cross the Router, queue and Distributor work, and the selected Node before the response reaches the client.
Animated field map
Grid Session and Trace Correlation
Persist the WebDriver session id, follow request spans through Grid, and attach resolved trace links to the test's failure evidence.
01 / session id
Test Session ID
The client records test identity and the returned WebDriver session id.
02 / router span
Router Span
The public Grid entry span receives and routes the WebDriver request.
03 / distributor span
Distributor Span
Session creation work matches capacity and coordinates the selected Node.
04 / node span
Node Span
The owning Node executes session creation or a later browser command.
05 / failure artifact
Correlated Failure Artifact
Backend trace ids and links enrich the report using session.id evidence.
Existing-session commands take a shorter logical route because the Router can use the Session Map to locate the owning Node. Their traces may not contain a Distributor span. The dashboard and report should describe the observed route rather than requiring every trace to have the same shape.
Enable tracing and structured events together
Tracing is enabled by default in documented Grid behavior, but production configuration should state the intent explicitly. Structured logs make trace fields machine-searchable, and Selenium notes that tracing must remain enabled for event logging.
[logging]
tracing = true
structured-logs = true
plain-logs = falseApply equivalent settings to every participating component. A traced Router with an uninstrumented or disconnected Node yields an incomplete path that can look like a propagation defect. Record component role, deployment revision, and config checksum as collector resource metadata or log-enrichment fields supported by the platform.
Before adopting an exporter recipe, run the promoted artifact's tracing help:
java -jar selenium-server.jar info tracingThis keeps exporter setup aligned with the shipped Selenium artifact. The Docker distribution also supports an OpenTelemetry exporter endpoint through its documented container configuration. Send all Grid roles to a trusted collector rather than configuring unrelated destinations per component.
Put a collector between Grid and the backend
An OpenTelemetry Collector provides one endpoint for Grid components and one controlled path to Jaeger or another tracing backend. It can batch, retry, authenticate, redact, and route telemetry according to infrastructure policy. Grid should not need backend credentials embedded in every Node image.
Use OTLP over the protocol supported by the current Selenium deployment and collector. Protect the route with network policy and TLS when it crosses a trust boundary. An exporter endpoint that is merely syntactically configured is not healthy; monitor accepted, rejected, queued, retried, and exported telemetry at the collector.
Keep tracing available when the backend is temporarily slow. Collector buffering must be bounded so telemetry pressure cannot exhaust Grid hosts. Decide explicitly whether to drop, back-pressure, or persist batches, and test that choice under backend outage conditions.
Capture the session identity in the test harness
The client knows the test id and receives the WebDriver session id. Persist both as soon as session creation succeeds, before page navigation or fixtures can fail. Returned capabilities identify the browser environment that actually matched.
import java.time.Instant;
import java.util.Map;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
static Map<String, String> sessionEvidence(
String testId,
String gridName,
RemoteWebDriver driver) {
Capabilities actual = driver.getCapabilities();
return Map.of(
"testId", testId,
"grid", gridName,
"webdriverSessionId", driver.getSessionId().toString(),
"browserName", actual.getBrowserName(),
"browserVersion", actual.getBrowserVersion(),
"capturedAt", Instant.now().toString());
}Write this map through the test framework's attachment or result API, not an ad hoc shared file that parallel tests can overwrite. Avoid storing the full capabilities object without redaction; provider options can contain tokens, tunnel names, internal URLs, or customer-like labels.
If session creation itself fails, there is no returned session id. Correlate that attempt using a unique safe request label, Grid identity, a narrow timestamp window, and the new-session trace fields actually emitted by the deployment. Do not fabricate a session id for failed creation.
Search event attributes by session.id
Selenium's documented event log shape includes traceId, spanId, eventName, and an attributes object. Session-scoped operations can include session.id. A normalized event stored by the backend can resemble this sanitized structure:
{
"traceId": "4f8b0c2a7d1e49e6a650dbecff109321",
"spanId": "27f35130f8f78ab2",
"eventName": "Session request execution complete",
"attributes": {
"http.method": "DELETE",
"http.status_code": 200,
"session.id": "9c1f-example-session"
}
}The values are illustrative, while the field relationship is the important part. Query the exact indexed attribute name produced by the collector transformation. Some backends flatten resource, span, and event attributes differently.
Return all relevant trace ids for the session within its execution window. A single trace link may explain the failed command but omit slow creation or broken deletion. Group results by operation and timestamp, then attach the most useful links plus the session-id query as a fallback.
Build a one-to-many correlation record
Keep a small durable record that maps test id and WebDriver session id to zero or more resolved traces. Each entry should include trace id, first and last timestamps, operation category, error flag, backend link, and correlation method. Mark whether the match came from exact session.id or a weaker failed-creation search.
Resolve asynchronously after the test because collectors and backends can ingest telemetry after the client result is written. Poll for a bounded interval, then publish an unresolved state rather than blocking the whole suite indefinitely. A later enrichment job can update the report if the reporting system supports it.
Do not use browser name or Node URI alone as a join key. Parallel sessions share those values. Time windows help constrain a search but are not unique evidence by themselves.
Distinguish creation, command, and teardown failures
A slow or failed new-session trace reveals queue, matching, Distributor, Node selection, driver startup, and browser startup work. A command trace after creation is more likely to reveal Router lookup, Node routing, browser command duration, or transport errors. A delete-session trace explains leaked slots and browser processes.
Attach the trace nearest the assertion failure, but also retain creation duration and teardown outcome. A test can fail because setup consumed most of its budget, then leak capacity because cleanup failed. Those are separate incidents even though one test result contains both.
When a trace ends at the Router, inspect downstream propagation and Session Map lookup. When it reaches the Node and records an exception, inspect Node, driver, and browser logs using the same session id. Trace spans identify the failing boundary; they do not replace component-specific logs.
Control cardinality, retention, and sensitive data
Session ids and test ids are high-cardinality values, which is appropriate for targeted traces but expensive as unrestricted metric labels. Keep them in trace and log attributes, not in long-lived metric dimensions. Aggregate metrics should use bounded labels such as Grid, browser family, component, and outcome.
Capabilities, URLs, exception messages, and HTTP metadata can contain secrets. Redact at the earliest practical collector stage and restrict raw trace access. Set retention based on investigation needs and incident policy, then keep only selected evidence for long-running defects.
Sampling policy must preserve the failures and latency cases the team expects to investigate. Test the actual backend query under that policy. A perfect correlation algorithm cannot find spans that were never retained.
Diagnose missing correlation systematically
If no traces arrive, check component tracing settings, exporter endpoint, DNS, TLS, collector receivers, and backend export. If traces arrive but stop at one component, compare that role's configuration and propagation path. If traces exist but session search returns none, inspect raw event attributes and collector transformations.
If test timestamps and trace timestamps disagree, verify clock synchronization and timezone handling while continuing to prefer exact identifiers. If only passing commands appear, examine sampling and error-status mapping. If the same session appears under multiple Grid environments, add an explicit Grid identity dimension to the query.
Exporter connection errors in Grid logs are an observability outage, not automatically a test failure. Alert them separately, because lost traces reduce diagnostic confidence even while browser sessions still execute.
Trace correlation checklist
- Enable tracing and structured event logging on every Grid role.
- Validate exporter setup with the promoted artifact's
info tracingoutput. - Route telemetry through a monitored, protected collector.
- Record test id and WebDriver session id immediately after creation.
- Preserve returned browser capabilities in a sanitized attachment.
- Query exact
session.idattributes for all traces in the session window. - Treat session-to-trace correlation as one-to-many.
- Separate creation, command, and delete-session trace links.
- Enrich reports asynchronously with a bounded wait.
- Keep session ids out of low-cardinality metric labels.
- Redact sensitive attributes and test sampling against real failures.
End every failure with a route to evidence
Correlation is successful when a failed test exposes its WebDriver session id and direct routes to the Grid requests that created, served, and deleted that session. Persist the client identifier first, preserve it through the telemetry pipeline, and resolve all matching traces rather than guessing one. The report can then move from "Grid failed" to the exact component and request boundary that needs attention.
// LIVE COURSE / THE TESTING ACADEMY
Playwright Automation Mastery
Go beyond Selenium. Master Playwright with JS/TS in 90 days.
From the instructor behind this guide.
Playwright jobs are growing 8x faster than Selenium. 90 days / 75+ live hrs / Tue-Thu-Sat 7 AM IST.
PRIMARY REFERENCES
Verify the details at the source
QABattle guides are practical explanations. Product behavior, standards, and APIs can change, so use these primary references for the canonical details.
- 01Selenium documentation
Selenium Project
Canonical WebDriver, Grid, waits, element, and browser automation guidance.
- 02WebDriver standard
W3C
The browser automation protocol specification behind WebDriver implementations.
FAQ / QUICK ANSWERS
Questions testers ask
Does a WebDriver session ID equal an OpenTelemetry trace ID?
No. A session ID identifies the browser session, while a trace ID identifies one distributed request flow. Session creation and later WebDriver commands can produce multiple traces associated with the same session.
Which value should a Selenium test store for Grid correlation?
Store the `RemoteWebDriver` session ID immediately after creation, along with test id, timestamp, requested environment, returned capabilities, and Grid identity. Use that session ID to find related trace events.
Does Selenium Grid include OpenTelemetry instrumentation?
Yes. Selenium Grid documents tracing with OpenTelemetry across server requests and exposes trace and span identifiers in its event logging when tracing and the relevant log output are enabled.
Why are Grid spans missing even though tests passed?
Check tracing configuration on every component, exporter endpoint reachability, collector health, sampling and retention policy, clock consistency, and whether the query searches the actual `session.id` attribute.
Should trace links be written directly into the test before driver creation?
Usually no, because the WebDriver session ID does not exist yet. Create the session, persist its ID, query the observability backend after telemetry arrives, and enrich the final failure artifact asynchronously.
RELATED GUIDES
Continue the learning route
GUIDE 01
Build a Selenium Grid Capacity Dashboard with GraphQL
Build a Selenium Grid GraphQL dashboard for node health, sessions, queue depth, compatible slot capacity, stale-data handling, and actionable alerts.
GUIDE 02
A Production TOML Baseline for Selenium Grid 4
Build a production Selenium Grid TOML baseline with explicit topology, registration trust, Router authentication, node stereotypes, logs, and health checks.
GUIDE 03
Tune Selenium Grid Session Queue Timeouts, Retries, and Batches
Tune Selenium Grid queue timeouts, retry intervals, batches, and polling with measured startup budgets, capability-aware analysis, and safe load tests.
GUIDE 04
Control DriverService Ports, Logs, and Process Lifecycles in Selenium 4
Configure Selenium DriverService ports and logs, own local driver processes safely, prevent leaks, and preserve useful startup failure evidence.