Networking
Recording HTTP requests from Dart with SophonzHttpClient, the sophonz_dio interceptor or recordNetworkRequest, and propagating the W3C traceparent header so backend traces join the app's requests.
Requests made from Dart do not pass through OkHttp or URLSession, so the native SDKs never see them. They are recorded by wrapping the client: SophonzHttpClient for the http package, SophonzInterceptor for Dio, or recordNetworkRequest for anything else. Each request becomes a network span with the URL, method, status, sizes and the traceparent header value sent to the server.
Choosing a client
| Client | Records requests | Sends traceparent |
|---|---|---|
SophonzHttpClient (http) | yes | on every request |
SophonzInterceptor (Dio) | yes | only while an OpenTelemetry span is current, or with the extra interceptor below |
recordNetworkRequest | what you pass | you add the header yourself |
http package
SophonzHttpClient is an http.BaseClient. Use it wherever an http.Client is expected.
import 'package:http/http.dart' as http;
import 'package:sophonz/sophonz.dart';
final http.Client client = SophonzHttpClient();
final response = await client.get(Uri.parse('https://api.example.com/orders'));To keep an existing client, such as one with retries or a custom HttpClient, wrap it:
final client = SophonzHttpClient(internalClient: RetryClient(http.Client()));close() closes the wrapped client.
What is recorded for each request:
| Field | Value |
|---|---|
| URL | request.url, in full. iOS removes the query string and fragment |
| Method | GET, POST, PUT, DELETE or PATCH; anything else is OTHER |
| Start, end | from send being called until the response headers arrive. Reading the body is not included |
| Bytes sent | request.contentLength, or 0 when unknown |
| Bytes received | the response Content-Length, or 0 when absent |
| Status | the response status code |
| Error | for a ClientException (connection refused, DNS failure), recorded as an incomplete request, then rethrown |
Dio
Add sophonz_dio as described in Installation, with the dependency_overrides entry. It supports Dio 4.x and 5.x.
import 'package:dio/dio.dart';
import 'package:sophonz_dio/sophonz_dio.dart';
final dio = Dio(BaseOptions(baseUrl: 'https://api.example.com'))
..interceptors.add(SophonzInterceptor());| Outcome | Recorded as |
|---|---|
| Response | completed request with the status code |
DioException with a response (such as a 404 under the default validateStatus) | completed request with that status code |
DioException without a response (connection error, timeout, cancel) | incomplete request with the error message |
Sizes are estimated. Bytes sent is the length of a String or List<int> body, or of the JSON encoding of a Map or List; FormData and streams count as 0. Bytes received is the Content-Length header, or the length of a plain or JSON response body when the header is absent.
Add SophonzInterceptor after interceptors that change the URL or headers, so it records the request as sent.
CAUTION — On Android, other HTTP methods are not recorded
The Android SDK accepts only standard method names, and the Dart layer maps everything except GET, POST, PUT, DELETE and PATCH to OTHER. On Android a HEAD or OPTIONS request is therefore dropped. iOS records it as OTHER.
Recording requests yourself
For a client with no wrapper, such as a gRPC channel or a platform channel to native networking, build the request after it completes.
import 'package:sophonz/sophonz.dart';
import 'package:sophonz/sophonz_api.dart';
final start = DateTime.now().millisecondsSinceEpoch;
try {
final result = await grpcClient.getOrder(request);
Sophonz.instance.recordNetworkRequest(
SophonzNetworkRequest.fromCompletedRequest(
url: 'https://grpc.example.com/orders.OrderService/GetOrder',
httpMethod: HttpMethod.post,
startTime: start,
endTime: DateTime.now().millisecondsSinceEpoch,
bytesSent: request.writeToBuffer().length,
bytesReceived: result.writeToBuffer().length,
statusCode: 200,
),
);
} catch (error) {
Sophonz.instance.recordNetworkRequest(
SophonzNetworkRequest.fromIncompleteRequest(
url: 'https://grpc.example.com/orders.OrderService/GetOrder',
httpMethod: HttpMethod.post,
startTime: start,
endTime: DateTime.now().millisecondsSinceEpoch,
errorDetails: error.toString(),
),
);
rethrow;
}| Parameter | fromCompletedRequest | fromIncompleteRequest |
|---|---|---|
url, httpMethod, startTime, endTime | required | required |
bytesSent, bytesReceived, statusCode | required | not taken; sent as -1 |
errorDetails | not taken | required |
traceId | optional | optional |
w3cTraceparent | optional; the header you sent | optional |
Times are epoch milliseconds.
Trace propagation
A traceparent header on the request lets the backend continue the same trace. The backend's server span becomes a child of the header's span ID, and the app's network span records the header value, so the request in the app and the handler on the server can be found together.
Where the header comes from
The wrappers never overwrite a traceparent that is already on the request. Otherwise:
| Situation | SophonzHttpClient | SophonzInterceptor |
|---|---|---|
| An OpenTelemetry span is current (see below) | a header for that span. On Android the native SDK generates a fresh value instead | a header for that span, built in Dart |
| No current span | a fresh value from the native SDK | not sent. A value is generated after the response and only recorded on the span |
Fresh values have random trace and span IDs with the sampled flag, for example 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01.
Sending traceparent with Dio
To send the header on every Dio request, add an interceptor in front of SophonzInterceptor. It can also limit the header to your own hosts.
import 'package:dio/dio.dart';
import 'package:sophonz/sophonz.dart';
import 'package:sophonz_dio/sophonz_dio.dart';
class TraceparentInterceptor extends Interceptor {
TraceparentInterceptor(this.hosts);
final Set<String> hosts;
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
if (hosts.contains(options.uri.host) &&
!options.headers.containsKey('traceparent')) {
final value = await Sophonz.instance.generateW3cTraceparent(null, null);
if (value != null) options.headers['traceparent'] = value;
}
handler.next(options);
}
}
final dio = Dio()
..interceptors.addAll([
TraceparentInterceptor({'api.example.com'}),
SophonzInterceptor(),
]);SophonzInterceptor sees the header already set and records that value on the network span.
Linking to your own span
To make a request part of a span you started through the OpenTelemetry API, run it with that span current:
import 'package:dartastic_opentelemetry_api/dartastic_opentelemetry_api.dart';
final tracer = OTelAPI.tracerProvider().getTracer('checkout');
final span = tracer.startSpan('submit-order');
try {
await tracer.withSpanAsync(span, () => dio.post('/orders', data: order));
} finally {
span.end();
}startSpan alone does not make a span current. Note the limits of spans created through the OpenTelemetry API, described in the API reference.
Which hosts receive the header
SophonzHttpClient adds the header to every request, including third-party APIs. For hosts that must not receive trace IDs, use a plain http.Client, or use Dio with the host-limited interceptor above.
Backend setup
The backend needs an OpenTelemetry SDK with the W3C Trace Context propagator, which is the default in the Sophonz backend SDKs and in OpenTelemetry generally. See Node.js, Python, Go or Java.
CORS does not apply. It is a browser rule, and a Flutter app on Android or iOS sends requests directly, so the server needs no Access-Control-Allow-Headers entry for traceparent. A reverse proxy or API gateway in front of the backend must pass the header through.
Next
- API reference —
recordNetworkRequestandgenerateW3cTraceparent - Examples — Dio and go_router in a complete app