Skip to main content

Network Monitoring

Network Capture​

The Embrace SDK automatically monitors network requests made through URLSession in your application, providing visibility into network performance, errors, and behavior.

How Network Monitoring Works​

The URLSessionCaptureService captures URLSession network requests and generates OpenTelemetry spans that:

  • Start when a URLSessionTask is created
  • End when the task receives a response or errors out
  • Include attributes like URL, status code, and timing information

This automatic instrumentation gives you immediate visibility into all network activity without requiring manual code changes.

Key Benefits​

  • Track network request timing and performance
  • Identify slow or failing API endpoints
  • Monitor request/response sizes
  • Troubleshoot network errors
  • Correlate network activity with user actions and app behavior

Data Captured​

For each network request, the SDK captures:

  • Request URL (with sensitive data optionally obfuscated)
  • HTTP method
  • Status code
  • Start and end time
  • Request size
  • Response size (when available)
  • Error information (for failed requests)

Configuration Options​

You can customize network monitoring behavior when initializing the Embrace SDK:

let urlSessionOptions = URLSessionCaptureService.Options(
requestsDataSource: MyDataSource(), // For obfuscating sensitive data
ignoredURLs: ["analytics.example.com"] // URLs to ignore
)

let services = CaptureServicesOptionsBuilder()
.addDefaults()
.addUrlSessionCaptureService(withOptions: urlSessionOptions)
.build()

let options = EmbraceIO.Options.withAppId(
appId,
platform: .native,
captureServices: services,
crashReporter: .embrace
)

do {
try EmbraceIO.start(options: options)
} catch { }

Tracing Header Injection​

The SDK can inject a W3C Traceparent header into network requests:

00-[trace_id]-[span_id]-[is_sampled]

This allows for distributed tracing across your frontend and backend systems, providing end-to-end visibility into request flows.

info

Traceparent injection must be enabled through the Embrace dashboard. If you're using the Embrace Dashboard and want this feature, enable it via Network Spans Forwarding settings or contact support@embrace.io.

For non-managed setups (using a custom EmbraceConfigurable), implement the traceparentInjectionEnabled property on your configurable object:

class MyConfig: EmbraceConfigurable {
var traceparentInjectionEnabled: Bool { true }
// ... other required properties
}

Limiting Injection to Specific Domains​

By default, when injection is enabled, the traceparent header is added to all captured requests. Use URLSessionCaptureService.Traceparent with onlyAllowDomains to restrict injection to first-party domains:

let captureServices = CaptureServicesOptionsBuilder()
.addDefaults()
.addUrlSessionCaptureService(withOptions: URLSessionCaptureService.Options(
traceparent: .init(onlyAllowDomains: ["api.example.com", "example.com"])
))
.build()

let options = EmbraceIO.Options.withAppId(
"YOUR_APP_ID",
captureServices: captureServices
)

do {
try EmbraceIO.start(options: options)
} catch { }

Domain matching rules:

  • Entries are bare hostnames — no protocol prefix, no leading ., no path (e.g. "example.com")
  • Each entry matches the exact host ("example.com") and any subdomain ("api.example.com")
  • Matching is case-insensitive
  • nil (the default) means all captured requests receive the header
  • An empty array means no requests receive the header
  • Invalid entries (empty strings, entries containing / or whitespace, entries with a leading .) are silently dropped. If all entries are invalid, the result is an empty list and no traceparent headers will be injected
  • To check for invalid entries, search your Xcode console output for allowedDomains
note

The injectTracingHeader property on URLSessionCaptureService.Options is deprecated. If you were previously setting it, you can safely remove it — server-side migration preserves your existing configuration.

Sensitive Data Handling​

To protect sensitive information in network requests, you can implement the URLSessionRequestsDataSource protocol:

info

This only affects the data captured by the Embrace SDK and does not modify the original request sent by your app.

class MyDataSource: NSObject, URLSessionRequestsDataSource {
func modifiedRequest(for request: URLRequest) -> URLRequest {
var newRequest = request

// Example: Obfuscate sensitive URLs
if let url = newRequest.url?.absoluteString, url.contains("user/password") {
// Create a modified URL with sensitive parts removed
let safeUrl = url.replacingOccurrences(of: "password=[^&]+", with: "password=***", options: .regularExpression)
newRequest.url = URL(string: safeUrl)
}

return newRequest
}
}

Ignoring Specific URLs​

You can prevent monitoring of certain URLs by adding them to the ignoredURLs list. Any request URL containing these strings will be completely ignored by the Embrace SDK:

URLSessionCaptureService.Options(
ignoredURLs: [
"analytics.example.com",
"metrics.myapp.com",
"logs.thirdparty.service"
]
)

Parenting Network Spans​

By default, each network span starts its own trace. You can parent network spans to another span to see the requests made during a flow (for example, checkout or login) inside that flow's trace.

The parent of a network span is chosen in this order. The first rule that applies wins:

  1. The parent returned by spanParent(for:currentParentContext:) in your URLSessionRequestsDataSource, if it returns .parent or .noParent.
  2. The span named in the request's traceparent header, if the request already has a well-formed one.
  3. The network span parent set with EmbraceIO.shared.setNetworkSpanParent(_:).
  4. No parent. The network span starts a new trace.

Setting a Network Span Parent​

Use setNetworkSpanParent(_:) to parent every network span started from now on to a span:

let span = EmbraceIO.shared.createSpan(
name: "checkout",
type: .performance
)

if let span {
EmbraceIO.shared.setNetworkSpanParent(span)
}

// Requests made here are parented to the "checkout" span
await performCheckout()

span?.end() // Also clears the network span parent

To parent network spans to a span the SDK didn't create, such as one from your own OpenTelemetry pipeline, pass its EmbraceSpanContext:

let context = EmbraceSpanContext(
spanId: otelSpan.context.spanId.hexString,
traceId: otelSpan.context.traceId.hexString
)

let token = EmbraceIO.shared.setNetworkSpanParent(context)

// Requests made here are parented to your span
await performCheckout()

EmbraceIO.shared.clearNetworkSpanParent(token)

How the network span parent works:

  • There is one network span parent at a time. Setting a new one replaces the previous one, and replacing a parent that is still active logs a warning.
  • The parent is cleared automatically when its span ends, and when the current user session ends. For a context whose span the SDK never sees end, call clearNetworkSpanParent(_:) when the flow ends.
  • clearNetworkSpanParent(_:) only clears the parent set with that token. It does nothing, and returns false, if the parent was already replaced or cleared.
  • Network spans that already started keep their parent.
  • A span that has already ended, or a context with invalid identifiers (span id other than 16 hexadecimal characters, trace id other than 32, or all zeros), is rejected with a warning and the previous parent stays.
  • Only network spans captured by the SDK are affected.
  • These methods are thread safe.
Choosing the Parent per Request​

To decide the parent of each request, implement spanParent(for:currentParentContext:) in your URLSessionRequestsDataSource. It returns an EmbraceNetworkSpanParent:

  • .parent(EmbraceSpanContext): Parent the network span to the span with this context. A context with invalid identifiers is ignored with a warning, as if .default was returned.
  • .noParent: Start a new trace, ignoring the request's traceparent header and the network span parent.
  • .default: Use the default rules described above.
class MyDataSource: URLSessionRequestsDataSource {
func modifiedRequest(for request: URLRequest) -> URLRequest {
return request
}

func spanParent(for request: URLRequest, currentParentContext: EmbraceSpanContext?) -> EmbraceNetworkSpanParent {
// Keep image downloads out of the current flow's trace
if request.url?.host == "images.example.com" {
return .noParent
}

return .default
}
}

currentParentContext is the context of the network span parent set with setNetworkSpanParent(_:), if any. The request is the one returned by modifiedRequest(for:).

warning

spanParent(for:currentParentContext:) is called synchronously on the thread that creates or resumes the URLSessionTask, which can be the main thread. Keep it fast and never block in it (no locks the app may hold while creating requests, DispatchQueue.main.sync or semaphores). Calls taking longer than a few milliseconds are logged as a warning.

The method has a default implementation that returns .default, so existing data sources don't need changes. It's called at most once per captured request, and not for requests in ignoredURLs.

note

When the SDK injects a traceparent header into a request that already has one, the existing header is replaced with the network span's. If the network span is in the trace named by the existing header, the new header keeps its trace-flags.

Best Practices​

  • Use the requestsDataSource to hide sensitive data like authentication tokens and PII

  • Use setNetworkSpanParent(_:) to group the requests made during a flow under that flow's span

  • Ignore analytics and other high-volume endpoints that aren't relevant for troubleshooting

  • Consider enabling trace header injection for end-to-end request tracing

  • Monitor response times to identify slow endpoints

  • Track error rates to find problematic services