### Start Python Mock Server Source: https://github.com/datadog/dd-sdk-ios/blob/develop/tools/http-server-mock/README.md Command to start the Python HTTP mock server from the command line. ```bash ./python/start_mock_server_py ``` -------------------------------- ### Benchmark Configuration File Example Source: https://github.com/datadog/dd-sdk-ios/blob/develop/BenchmarkTests/README.md Example content for the Benchmark.local.xcconfig file, specifying sensitive client tokens and IDs required for building the runner application. ```ini CLIENT_TOKEN= RUM_APPLICATION_ID= API_KEY= ``` -------------------------------- ### Install UI Test Pods Source: https://github.com/datadog/dd-sdk-ios/blob/develop/IntegrationTests/README.md Run this command to set up the environment for UI integration tests by installing CocoaPods dependencies. ```bash make ui-test-podinstall ``` -------------------------------- ### Minimal DatadogCoreProxy Example Source: https://github.com/datadog/dd-sdk-ios/wiki/How-to-use-`DatadogCoreProxy`-in-tests? This example demonstrates the minimal setup for using DatadogCoreProxy in tests. Ensure `core.flushAndTearDown()` is called after each test to prevent leaks. ```swift let core = DatadogCoreProxy(context: .mockWith(service: "foo-bar")) defer { core.flushAndTearDown() } core.register(feature: LoggingFeature.mockAny()) let logger = Logger.builder.build(in: core) logger.debug("message") let events = core.waitAndReturnEvents(of: LoggingFeature.self, ofType: LogEvent.self) XCTAssertEqual(events[0].serviceName, "foo-bar") ``` -------------------------------- ### Create a Scenario for Logs Source: https://github.com/datadog/dd-sdk-ios/blob/develop/BenchmarkTests/README.md Example of a scenario conforming to the Scenario protocol, initializing the SDK with benchmark configuration and enabling Logs. ```swift import Foundation import UIKit import DatadogCore import DatadogLogs struct LogsScenario: Scenario { /// The initial view-controller of the scenario let initialViewController: UIViewController = LoggerViewController() /// Start instrumenting the application by enabling the Datadog SDK and /// its Features. /// /// - Parameter info: The application information to use during SDK /// initialisation. func instrument(with info: AppInfo) { Datadog.initialize( with: .benchmark(info: info), // SDK init with the benchmark configuration trackingConsent: .granted ) Logs.enable() } } ``` -------------------------------- ### Correct RUM Configuration Initialization Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/LLM_FEATURE_DOCS_GUIDELINES.md Demonstrates the correct way to initialize RUM Configuration, listing all options in the proper order with valid example values. ```swift RUM.Configuration( applicationID: "", sessionSampleRate: 100.0, uiKitViewsPredicate: DefaultUIKitRUMViewsPredicate() // ... all other options in order ) ``` -------------------------------- ### Update SPMProject Setup Source: https://github.com/datadog/dd-sdk-ios/blob/develop/SmokeTests/spm/README.md Use this command to update the setup in SPMProject.xcodeproj and apply changes back to SPMProject.xcodeproj.src for committing. ```bash make create-src-from-xcodeproj ``` -------------------------------- ### Initialize Datadog SDK and Enable Logs Source: https://github.com/datadog/dd-sdk-ios/blob/develop/E2ETests/README.md Example of a Swift scenario initializing the Datadog SDK with e2e configuration and enabling the Logs feature. This scenario returns a root view-controller. ```swift import Foundation import UIKit import DatadogCore import DatadogLogs struct SessionReplayWebViewScenario: Scenario { func start(info: TestInfo) -> UIViewController { Datadog.initialize( with: .e2e(info: info), // SDK init with the e2e configuration trackingConsent: .granted ) Logs.enable() return LoggerViewController() } } ``` -------------------------------- ### Feature Documentation File Structure Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/LLM_FEATURE_DOCS_GUIDELINES.md Examples of feature documentation file paths within the repository. ```markdown DatadogRUM/RUM_FEATURE.md DatadogSessionReplay/SESSION_REPLAY_FEATURE.md DatadogTrace/TRACE_FEATURE.md # (future) DatadogLogs/LOGS_FEATURE.md # (future) DatadogWebViewTracking/WEBVIEW_FEATURE.md # (future) ``` -------------------------------- ### Run Snapshot Comparison Tests Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogSessionReplay/SRSnapshotTests/README.md Execute snapshot comparison tests locally. Requires GitHub CLI to be installed and authorized. ```bash make sr-snapshot-test ``` -------------------------------- ### Enable RUM Product in Datadog SDK Source: https://github.com/datadog/dd-sdk-ios/blob/develop/MIGRATION.md Import the DatadogRUM module and enable the RUM product with your Application ID. This is the first step to start collecting RUM data. ```swift import DatadogRUM RUM.enable( with: RUM.Configuration(applicationID: "") ) ``` -------------------------------- ### Push Snapshot Files Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogSessionReplay/SRSnapshotTests/README.md Push local PNG snapshot files to the remote repository. Requires GitHub CLI to be installed and authorized. ```bash make sr-snapshots-push ``` -------------------------------- ### Enable WebView Tracking in Datadog SDK Source: https://github.com/datadog/dd-sdk-ios/blob/develop/MIGRATION.md Import the DatadogWebViewTracking module and use `WebViewTracking.enable(webView:)` to start tracking events from a WKWebView. RUM and/or Logs must also be enabled. ```swift import WebKit import DatadogWebViewTracking let webView = WKWebView(...) WebViewTracking.enable(webView: webView) ``` -------------------------------- ### Manual Recording Control for Session Replay Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogSessionReplay/SESSION_REPLAY_FEATURE.md Manually start or stop Session Replay recording. Useful when `startRecordingImmediately` is set to `false` or for dynamic control based on application state. ```swift // 4. (Optional) Manual recording control // Use cases: // - Start recording later if startRecordingImmediately: false // - Stop/resume recording dynamically based on app state SessionReplay.startRecording() SessionReplay.stopRecording() ``` -------------------------------- ### Get Metatype of a Variable in Swift Source: https://github.com/datadog/dd-sdk-ios/wiki/Get-type-information-in-Swift-with-generics Use `type(of:)` to get the metatype of a variable. This is the basic way to inspect type information. ```swift let metatype = type(of: variable) ``` -------------------------------- ### Initialize Datadog SDK v1.x Source: https://github.com/datadog/dd-sdk-ios/blob/develop/MIGRATION.md Shows the initialization pattern for Datadog SDK v1.x using the Builder pattern. ```swift import Datadog Datadog.initialize( appContext: .init(), trackingConsent: .granted, configuration: Datadog.Configuration .builderUsing( clientToken: "", environment: "" ) .set(serviceName: "") .build() ) ``` -------------------------------- ### Initialize Datadog Core and Enable RUM Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogRUM/RUM_FEATURE.md This snippet shows the essential steps to initialize the Datadog Core SDK and then configure and enable the RUM feature. Ensure Datadog Core is initialized before enabling RUM. ```swift import DatadogCore import DatadogRUM // 1. Initialize Core SDK first Datadog.initialize( with: Datadog.Configuration( clientToken: "", env: "" ), trackingConsent: .granted ) // 2. Configure and enable RUM RUM.enable( with: RUM.Configuration( applicationID: "", // Session sampling: 100 = all sessions tracked, 0 = none tracked // Default: 100.0 sessionSampleRate: 100.0, // UIKit automatic view tracking - provide predicate to enable // Default: nil (disabled) // Or use custom: MyCustomViewsPredicate() uiKitViewsPredicate: DefaultUIKitRUMViewsPredicate(), // UIKit automatic action tracking - provide predicate to enable // Default: nil (disabled) // Or use custom: MyCustomActionsPredicate() uiKitActionsPredicate: DefaultUIKitRUMActionsPredicate(), // SwiftUI automatic view tracking - provide predicate to enable // Default: nil (disabled) // Or use custom: MyCustomViewsPredicate() // Note: Also requires uiKitViewsPredicate for SwiftUI tracking to work correctly swiftUIViewsPredicate: DefaultSwiftUIRUMViewsPredicate(), // SwiftUI automatic action tracking - provide predicate to enable // Default: nil (disabled) // Or use custom: MyCustomActionsPredicate() // Note: Also requires uiKitActionsPredicate for SwiftUI tracking to work correctly swiftUIActionsPredicate: DefaultSwiftUIRUMActionsPredicate(isLegacyDetectionEnabled: true), // Automatic network resource tracking - provide config to enable // Default: nil (disabled) urlSessionTracking: RUM.Configuration.URLSessionTracking( // Optional: Enable distributed tracing for first-party hosts firstPartyHostsTracing: .trace( hosts: ["api.example.com", "example.com"], sampleRate: 100.0 ), // Optional: Add custom attributes to resources resourceAttributesProvider: { request, response, data, error in return ["custom.attribute": "value"] } ), // Track user frustrations (error taps following errors) // Default: true trackFrustrations: true, // Track events when no view is active (creates background view) // Default: false // Warning: May increase session count and billing trackBackgroundEvents: false, // Long task threshold: report tasks on main thread exceeding duration // Default: 0.1 (100ms) // Set to nil or 0 to disable longTaskThreshold: 0.1, // App hang threshold: report hangs exceeding duration // Default: nil (disabled) // Minimum: 0.1 seconds // Requires Crash Reporting for stack traces appHangThreshold: 2.0, // Track watchdog terminations as RUM errors // Default: false trackWatchdogTerminations: false, // Mobile vitals collection frequency // Default: .average // Options: .frequent (100ms), .average (500ms), .rare (1000ms), or nil (disabled) vitalsUpdateFrequency: .average, // Time-to-Network-Settled predicate: classify resources for TNS metric // Default: TimeBasedTNSResourcePredicate() (resources within 100ms of view start) networkSettledResourcePredicate: TimeBasedTNSResourcePredicate(threshold: 0.1), // Interaction-to-Next-View predicate: classify last interaction for INV metric // Default: TimeBasedINVActionPredicate() (actions within 3s of next view) // Set to nil to disable INV metric nextViewActionPredicate: TimeBasedINVActionPredicate(maxTimeToNextView: 3.0), // Event mappers: modify events before sending // viewEventMapper can modify but NOT drop views (non-optional return) viewEventMapper: { viewEvent in var modified = viewEvent // Modify view event return modified }, // Other event mappers can drop events by returning nil resourceEventMapper: { resourceEvent in var modified = resourceEvent // Scrub sensitive data modified.resource.url = scrubURL(modified.resource.url) return modified // or return nil to drop }, // Also available: errorEventMapper, actionEventMapper, longTaskEventMapper // Session start callback onSessionStart: { sessionId, isDiscarded in print("Session \(sessionId) started, sampled out: \(isDiscarded)") }, // Custom RUM intake endpoint // Default: nil (uses Datadog intake) customEndpoint: nil, ) ) ``` -------------------------------- ### Pull Snapshot Files Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogSessionReplay/SRSnapshotTests/README.md Pull PNG snapshot files from the remote repository. Requires GitHub CLI to be installed and authorized. ```bash make sr-snapshots-pull ``` -------------------------------- ### Handling ApplicationLaunch View Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/TESTING.md Shows how to drop or assert on the synthetic 'ApplicationLaunch' view generated by the SDK. This view captures events before the first user-defined view. ```swift // Strip the ApplicationLaunch view (throws if it's missing — serves as an assertion too) let views = try session.views.dropApplicationLaunchView() // Or assert-then-index when you need to inspect the launch view itself XCTAssertTrue(session.views[0].isApplicationLaunchView()) let userViews = Array(session.views.dropFirst()) ``` -------------------------------- ### Open Benchmark Tests Project Source: https://github.com/datadog/dd-sdk-ios/blob/develop/BenchmarkTests/README.md Command to open the benchmark tests project with the correct Xcode environment. ```bash make benchmark-tests-open ``` -------------------------------- ### Generic Metatype Function in Swift (Corrected) Source: https://github.com/datadog/dd-sdk-ios/wiki/Get-type-information-in-Swift-with-generics Casting the generic type to `Any` before getting its metatype resolves the issue, allowing retrieval of the concrete type information. ```swift func metatypeName(of variable: T) -> String { let metatype = type(of: variable as Any) // casting to Any fixes the issue! return "\(metatype)" } metatypeName(of: variable) // returns "StructThatILOVE"! 🙌 ``` -------------------------------- ### Initialize Datadog SDK Core Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Bootstraps the shared SDK instance. Must be called on the main thread before enabling any feature. Returns a DatadogCoreProtocol instance that can be used to associate features with a named instance. ```swift import DatadogCore // Basic initialization (default US1 site) Datadog.initialize( with: Datadog.Configuration( clientToken: "pub1234567890abcdef", env: "production", site: .us1, service: "ios-app", batchSize: .medium, uploadFrequency: .average, backgroundTasksEnabled: true ), trackingConsent: .pending // Wait for user consent before collecting data ) // Named secondary instance (e.g., for a separate Datadog org) let secondaryCore = Datadog.initialize( with: Datadog.Configuration( clientToken: "pub_secondary_token", env: "staging", site: .eu1 ), trackingConsent: .granted, instanceName: "secondary" ) // Check initialization state if Datadog.isInitialized() { print("SDK is running") } // Tear down when no longer needed Datadog.stopInstance() ``` -------------------------------- ### Enable Datadog Core, RUM, and Session Replay Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogSessionReplay/SESSION_REPLAY_FEATURE.md Initialize the Datadog SDK, enable RUM with necessary view and action predicates, and then enable Session Replay with custom configuration for sampling, privacy, and feature flags. Ensure RUM is enabled before Session Replay. ```swift import DatadogCore import DatadogRUM import DatadogSessionReplay // 1. Initialize Core SDK first Datadog.initialize( with: Datadog.Configuration( clientToken: "", env: "" ), trackingConsent: .granted ) // 2. Enable RUM first (required for Session Replay) // Session Replay requires view and action tracking to be enabled RUM.enable( with: RUM.Configuration( applicationID: "", // For pure UIKit apps: UIKit predicates are enough uiKitViewsPredicate: DefaultUIKitRUMViewsPredicate(), uiKitActionsPredicate: DefaultUIKitRUMActionsPredicate(), // For SwiftUI or mixed apps: Both UIKit AND SwiftUI predicates needed swiftUIViewsPredicate: DefaultSwiftUIRUMViewsPredicate(), swiftUIActionsPredicate: DefaultSwiftUIRUMActionsPredicate() ) ) // 3. Enable Session Replay SessionReplay.enable( with: SessionReplay.Configuration( // Sampling rate for Session Replay (applied ON TOP of RUM session sampling) // Example: 80% RUM × 20% SR = 16% of total sessions have replay // Default: 100.0 replaySampleRate: 100.0, // Text and input masking level // Default: .maskAll // Options: // .maskSensitiveInputs - Show all texts except sensitive inputs (passwords) // .maskAllInputs - Mask all input fields (textfields, switches, checkboxes) // .maskAll - Mask all texts and inputs (labels, etc.) textAndInputPrivacyLevel: .maskAll, // Image masking level // Default: .maskAll // Options: // .maskNonBundledOnly - Only show bundled images (SF Symbols, UIImage(named:)) // .maskAll - No images recorded // .maskNone - All images recorded (including downloaded/generated) imagePrivacyLevel: .maskAll, // Touch interaction masking // Default: .hide // Options: // .show - Show all user touches // .hide - Hide all user touches touchPrivacyLevel: .hide, // Start recording automatically when enabled // Default: true // If false, call SessionReplay.startRecording() manually startRecordingImmediately: true, // Custom endpoint for replay data // Default: nil (uses Datadog intake) customEndpoint: nil, // Feature flags for experimental features // Default: [.swiftui: false] featureFlags: [ .swiftui: true // Enable SwiftUI recording (experimental) ] ) ) ``` -------------------------------- ### Generic Metatype Function in Swift (Initial Attempt) Source: https://github.com/datadog/dd-sdk-ios/wiki/Get-type-information-in-Swift-with-generics This function attempts to get the metatype of a generic type. It shows the unexpected behavior when the variable is of a protocol type. ```swift func metatypeName(of variable: T) -> String { let metatype = type(of: variable) return "\(metatype)" } protocol ProtocolThatIHATE {} struct StructThatILOVE: ProtocolThatIHATE {} let variable: ProtocolThatIHATE = StructThatILOVE() metatypeName(of: variable) // returns "ProtocolThatIHATE" ???!!?! ``` -------------------------------- ### Initialize Datadog SDK Source: https://github.com/datadog/dd-sdk-ios/blob/develop/MIGRATION.md Initialize the Datadog SDK as early as possible in your application's lifecycle, typically in the AppDelegate. Ensure you replace placeholder values with your actual client token, environment, and service name. ```swift import DatadogCore Datadog.initialize( with: Datadog.Configuration( clientToken: "", env: "", service: "" ), trackingConsent: .granted ) ``` -------------------------------- ### Manual RUM Event Tracking Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogRUM/RUM_FEATURE.md Use the RUM Monitor for manual tracking of views and errors. Start and stop views, and add custom errors with source information. ```swift let monitor = RUMMonitor.shared() // Start a view monitor.startView(key: "ProductList", name: "Product List Screen") // Add custom error monitor.addError(message: "Failed to load products", source: .network) // Stop the view monitor.stopView(key: "ProductList") ``` -------------------------------- ### Verify Server State and Record Requests in Swift Source: https://github.com/datadog/dd-sdk-ios/blob/develop/tools/http-server-mock/README.md Swift code to connect to the mock server, obtain a recording session, send a request, and retrieve recorded requests for verification. ```swift import HTTPServerMock let serverProcessRunner = ServerProcessRunner(serverURL: "127.0.0.1:8000") guard let serverProcess = serverProcessRunner.waitUntilServerIsReachable() else { fatalError("Cannot reach the server.") } let server = ServerMock(serverProcess: serverProcess) let session = server.obtainUniqueRecordingSession() # now, from client's code send some request(s) to `session.recordingURL` # e.g. `POST http://127.0.0.1:8000/resource/1` with "hello world" HTTP body let recordedRequests = try session.getRecordedRequests() XCTAssertTrue(recordedRequests[0].path.hasSuffix("/resource/1")) XCTAssertEqual(recordedRequests[0].httpBody, "hello world".data(using: .utf8)!) ``` -------------------------------- ### Initialize Datadog SDK with RUM Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/sdk_performance.md Initializes the Datadog SDK with basic RUM instrumentation for tracking views, actions, and resources. Ensure trackingConsent, applicationID, and clientToken are properly configured. ```swift Datadog.initialize( appContext: .init(), trackingConsent: trackingConsent, configuration: .builderUsing( rumApplicationID: applicationID, clientToken: clientToken, environment: "benchmark" ) .enableLogging(true) .enableRUM(true) .enableTracing(true) .trackUIKitRUMViews() .trackUIKitRUMActions() .trackURLSession() .set(rumSessionsSamplingRate: 100) .set(loggingSamplingRate: 100) .set(loggingSamplingRate: 100) .set(customRUMEndpoint: URL(string: "http://172.16.10.112:8000/rum")!) .set(customLogsEndpoint: URL(string: "http://172.16.10.112:8000/logs")!) .build() ) Datadog.verbosityLevel = .debug DatadogTracer.initialize( configuration: .init(customIntakeURL: URL(string: "http://172.16.10.112:8000/span")!) ) logger = DatadogLogger.builder.build() ``` -------------------------------- ### Swift Module API Surface Example Source: https://github.com/datadog/dd-sdk-ios/blob/develop/tools/api-surface/README.md This Swift code defines a class `Car` with an enum `Manufacturer`, an internal `Engine` struct, and a public extension. The output demonstrates the extracted public API surface. ```swift import Foundation public class Car { public enum Manufacturer: String { case manufacturer1 case manufacturer2 case manufacturer3 } private let engine = Engine() public init( manufacturer: Manufacturer ) {} public func startEngine() -> Bool { engine.start() } public func stopEngine() -> Bool { engine.stop() } } internal struct Engine { func start() -> Bool { true } func stop() -> Bool { true } } public extension Car { var price: Int { 100 } } ``` ```text public class Car public enum Manufacturer: String case manufacturer1 case manufacturer2 case manufacturer3 public init(manufacturer: Manufacturer) public func startEngine() -> Bool public func stopEngine() -> Bool public extension Car var price: Int ``` -------------------------------- ### Complete Setter Swizzle Pattern with Guards Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/SWIZZLING.md Combines nil, type, and re-entrancy guards for safely swizzling property setters that install internal proxies. Ensures correct behavior when the property is reassigned or when third-party swizzles interfere. ```swift private static var proxyKey: Void? private static var objectsBeingSet: Set = [] // Inside swizzle closure: // 1. Nil guard — just forward nil; the proxy will be released automatically // when the previous value is eventually deallocated (see Pattern 4). guard let value = value else { previousImplementation(object, selector, nil) return } // 2. Type guard — don't re-wrap when our proxy comes back directly if value is OurProxy { previousImplementation(object, selector, value) return } // 3. Re-entrancy guard — break cycles from third-party swizzle re-entry let objectID = ObjectIdentifier(object) guard !Self.objectsBeingSet.contains(objectID) else { previousImplementation(object, selector, value) return } Self.objectsBeingSet.insert(objectID) defer { Self.objectsBeingSet.remove(objectID) } // 4. Normal path — create or reuse proxy keyed on value (see Pattern 4 below) previousImplementation(object, selector, wrappedValue) ``` -------------------------------- ### Discover Server Address Source: https://github.com/datadog/dd-sdk-ios/blob/develop/tools/http-server-mock/README.md Command to find the IP address and port the mock server is listening on. ```bash ./python/server_address.py ``` -------------------------------- ### Transparent Getter Swizzle for Wrapped Values Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/SWIZZLING.md Swizzles the getter to unwrap internal proxies, ensuring user code sees the original value. This is crucial when the setter installs a wrapper, preventing issues with type checking and delegate identity comparisons. ```swift // Getter swizzle — mirror every setter swizzle that installs a proxy swizzle(getterMethod) { previousImplementation -> Signature in return { object in let value = previousImplementation(object, Self.selector) if let proxy = value as? InternalProxy { return proxy.originalValue } return value } } ``` -------------------------------- ### Manual RUM Instrumentation with RUMMonitor.shared() Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Obtain the RUM monitor for manual instrumentation of view lifecycles, errors, resources, and actions. Supports key-based view tracking on all platforms and `UIViewController`-based tracking on iOS/tvOS. Manual resource tracking requires starting and stopping the resource with specific details. ```swift import DatadogRUM let monitor = RUMMonitor.shared() // MARK: - View lifecycle (key-based, works on all platforms including watchOS) monitor.startView(key: "checkout", name: "Checkout Screen", attributes: ["step": "cart"]) monitor.addTiming(name: "products-loaded") monitor.stopView(key: "checkout") // UIViewController-based (iOS/tvOS only) monitor.startView(viewController: self, name: "Profile", attributes: [:]) monitor.stopView(viewController: self) // MARK: - Errors monitor.addError( message: "Payment declined", type: "PaymentError", source: .source, attributes: [RUM.Attributes.errorFingerprint: "payment-declined-v2"] ) monitor.addError(error: someSwiftError, source: .network, attributes: [:]) // MARK: - Resources (manual network tracking) let resourceKey = "https://api.example.com/cart" monitor.startResource(resourceKey: resourceKey, url: URL(string: resourceKey)!) monitor.stopResource(resourceKey: resourceKey, statusCode: 200, kind: .fetch, size: 2048, attributes: [:]) monitor.stopResourceWithError(resourceKey: resourceKey, error: networkError, response: nil, attributes: [:]) // MARK: - Actions monitor.addAction(type: .tap, name: "Place Order", attributes: ["order_value": 99.99]) monitor.startAction(type: .swipe, name: "Image Gallery Swipe", attributes: [:]) monitor.stopAction(type: .swipe, name: nil, attributes: [:]) // MARK: - Feature flags monitor.addFeatureFlagEvaluation(name: "new_checkout_flow", value: true) // MARK: - Session management monitor.currentSessionID { sessionID in print("Active session: \(sessionID ?? "none")") } monitor.stopSession() // MARK: - View-scoped attributes monitor.addViewAttribute(forKey: "ab_variant", value: "B") monitor.addAttribute(forKey: "user_segment", value: "power-user") ``` -------------------------------- ### Carthage Framework Linking for Datadog SDK Source: https://github.com/datadog/dd-sdk-ios/blob/develop/MIGRATION.md Link the necessary Datadog SDK frameworks in Xcode when using Carthage. ```text github "DataDog/dd-sdk-ios" ``` ```text DatadogInternal.xcframework DatadogCore.xcframework ``` ```text DatadogLogs.xcframework DatadogTrace.xcframework DatadogRUM.xcframework DatadogCrashReporting.xcframework + CrashReporter.xcframework DatadogWebViewTracking.xcframework DatadogObjc.xcframework ``` -------------------------------- ### Enable and Configure Datadog Trace v2.0 Source: https://github.com/datadog/dd-sdk-ios/blob/develop/MIGRATION.md Enables the Trace product and accesses the shared Tracer instance in Datadog SDK v2.0. The SDK must be initialized prior to enabling any product. ```swift import DatadogTrace Trace.enable( with: Trace.Configuration(...) ) ``` ```swift import DatadogTrace let tracer = Tracer.shared() ``` -------------------------------- ### Initialize Secondary Datadog SDK Instance Source: https://github.com/datadog/dd-sdk-ios/blob/develop/MIGRATION.md Initialize a secondary Datadog SDK instance with a unique name to support multiple SDK instances within the application. This allows for isolated configurations and usage by third-party libraries. ```swift import DatadogCore import DatadogRUM import DatadogLogs import DatadogTrace let core = Datadog.initialize( with: configuration, trackingConsent: trackingConsent, instanceName: "my-instance" ) RUM.enable( with: RUM.Configuration(applicationID: ""), in: core ) Logs.enable(in: core) Trace.enable(in: core) ``` -------------------------------- ### Datadog.initialize Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Initializes the shared SDK instance. This must be called on the main thread before enabling any feature. It returns a DatadogCoreProtocol instance for associating features with a named instance. ```APIDOC ## Datadog.initialize ### Description Bootstraps the shared SDK instance. Must be called on the main thread before enabling any feature. Returns a `DatadogCoreProtocol` instance that can be used to associate features with a named instance. ### Usage ```swift import DatadogCore // Basic initialization (default US1 site) Datadog.initialize( with: Datadog.Configuration( clientToken: "pub1234567890abcdef", env: "production", site: .us1, service: "ios-app", batchSize: .medium, uploadFrequency: .average, backgroundTasksEnabled: true ), trackingConsent: .pending // Wait for user consent before collecting data ) // Named secondary instance (e.g., for a separate Datadog org) let secondaryCore = Datadog.initialize( with: Datadog.Configuration( clientToken: "pub_secondary_token", env: "staging", site: .eu1 ), trackingConsent: .granted, instanceName: "secondary" ) // Check initialization state if Datadog.isInitialized() { print("SDK is running") } // Tear down when no longer needed Datadog.stopInstance() ``` ``` -------------------------------- ### Open Scenario via Deep Link Source: https://github.com/datadog/dd-sdk-ios/blob/develop/BenchmarkTests/README.md Command to open a specific benchmark scenario and run using the simctl command-line tool. ```bash xcrun simctl openurl booted 'bench://start?scenario=&run=' ``` -------------------------------- ### Enable and Configure Datadog Logs v2.0 Source: https://github.com/datadog/dd-sdk-ios/blob/develop/MIGRATION.md Enables the Logs product and creates a logger instance in Datadog SDK v2.0. Ensure the SDK is initialized before enabling any product. ```swift import DatadogLogs Logs.enable(with: Logs.Configuration(...)) ``` ```swift import DatadogLogs let logger = Logger.create( with: Logger.Configuration(name: "") ) ``` -------------------------------- ### Incorrect RUM Configuration Initialization Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/LLM_FEATURE_DOCS_GUIDELINES.md Illustrates common mistakes in RUM Configuration initialization, such as options being out of order or missing. ```swift RUM.Configuration( applicationID: "...", trackFrustrations: true, // Wrong position sessionSampleRate: 100.0, // Missing options ) ``` -------------------------------- ### Apache License Header Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/CONVENTIONS.md All source files must include the Apache License header. ```swift /* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-Present Datadog, Inc. */ ``` -------------------------------- ### Run api-surface SPM Command Source: https://github.com/datadog/dd-sdk-ios/blob/develop/tools/api-surface/README.md Use this command to list the public API surface of a Swift Package Manager library. Specify the library name and its path. ```bash api-surface spm --library-name Foo --path ./Foo ``` -------------------------------- ### Datadog.Configuration Source: https://context7.com/datadog/dd-sdk-ios/llms.txt The SDK Configuration Object allows control over batching behavior, upload frequency, data encryption, proxy settings, and the target Datadog site. ```APIDOC ## Datadog.Configuration ### Description Controls batching behavior, upload frequency, data encryption, proxy settings, and the target Datadog site. ### Usage ```swift import DatadogCore var config = Datadog.Configuration( clientToken: "pub1234567890abcdef", env: "production", site: .us1, // .us1, .us3, .us5, .eu1, .ap1, .gov service: "com.example.myapp", // defaults to bundle identifier version: "3.2.1", // overrides CFBundleShortVersionString batchSize: .small, // .small | .medium | .large uploadFrequency: .frequent, // .frequent | .average | .rare batchProcessingLevel: .high, // .low | .medium | .high (max batches per cycle) backgroundTasksEnabled: true, // use UIApplication background tasks for uploads proxyConfiguration: [ kCFNetworkProxiesHTTPProxy as AnyHashable: "proxy.example.com", kCFNetworkProxiesHTTPPort as AnyHashable: 8080 ] ) // Enable on-disk encryption config.encryption = MyAESEncryption() // implement DatadogInternal.DataEncryption Datadog.initialize(with: config, trackingConsent: .granted) ``` ``` -------------------------------- ### Tracer.shared().startSpan — Manual Span Creation Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Obtains the OpenTracing-compatible tracer and creates custom spans to measure operations. Supports simple spans, child spans with parent context, logging events, and manual sampling overrides. ```APIDOC ## `Tracer.shared().startSpan` — Manual Span Creation Obtains the OpenTracing-compatible tracer and creates custom spans to measure operations. ```swift import DatadogTrace let tracer = Tracer.shared() // Simple span let span = tracer.startSpan(operationName: "data-decryption") defer { span.finish() } span.setTag(key: SpanTags.resource, value: "UserProfile") span.setTag(key: "encryption.algorithm", value: "AES-256") // Child span with parent context let parent = tracer.startSpan(operationName: "checkout") let child = tracer.startSpan( operationName: "validate-stock", childOf: parent.context, tags: ["sku": "PROD-001", "qty": 5] ) child.finish() parent.setTag(key: "order.total_usd", value: 149.99) parent.finish() // Log structured events onto a span let networkSpan = tracer.startSpan(operationName: "api-call") networkSpan.log(fields: [ OTLogFields.event: "error", OTLogFields.errorKind: "NetworkError", OTLogFields.message: "Timeout after 30s" ]) networkSpan.setTag(key: "error", value: true) networkSpan.finish() // Mark for manual sampling override span.setTag(key: SpanTags.manualKeep, value: true) ``` ``` -------------------------------- ### SessionReplay.enable Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Enables Session Replay to record pixel-perfect replays of user sessions with customizable privacy controls. Requires RUM to be enabled. ```APIDOC ## SessionReplay.enable — Enable Session Replay Records pixel-perfect replays of user sessions with fine-grained privacy controls for text/inputs, images, and touch interactions. Requires RUM to be enabled. iOS only. ### Usage ```swift import DatadogCore import DatadogRUM import DatadogSessionReplay SessionReplay.enable( with: SessionReplay.Configuration( replaySampleRate: 20, // record 20% of RUM sessions textAndInputPrivacyLevel: .maskSensitiveInputs, // .maskAll | .maskAllInputs | .maskSensitiveInputs imagePrivacyLevel: .maskNonBundledOnly, // .maskAll | .maskNonBundledOnly | .maskNone touchPrivacyLevel: .show, // .hide | .show startRecordingImmediately: false, // defer start to manual call featureFlags: [.swiftui: true] // enable SwiftUI recording (experimental) ) ) // Manually control recording lifecycle SessionReplay.startRecording() SessionReplay.stopRecording() // Per-view privacy overrides using UIView extension import UIKit passwordTextField.dd.sessionReplayPrivacyOverrides.textAndInputPrivacy = .maskAll avatarImageView.dd.sessionReplayPrivacyOverrides.imagePrivacy = .maskNone sensitiveContainer.dd.sessionReplayPrivacyOverrides.hide = true ``` ``` -------------------------------- ### DatadogCoreProxy Usage Pattern Source: https://github.com/datadog/dd-sdk-ios/blob/develop/docs/TESTING.md Demonstrates how to use DatadogCoreProxy to intercept and assert on SDK events. Ensure `core.flushAndTearDown()` is called using `defer`. ```swift let core = DatadogCoreProxy(context: .mockWith(service: "test-service")) defer { core.flushAndTearDown() } // MUST be in defer RUM.enable(with: config, in: core) let monitor = RUMMonitor.shared(in: core) monitor.startView(key: "view1") monitor.stopView(key: "view1") let session = try RUMSessionMatcher .groupMatchersBySessions(try core.waitAndReturnRUMEventMatchers()) .takeSingle() let views = try session.views.dropApplicationLaunchView() XCTAssertEqual(views.count, 1) XCTAssertEqual(views[0].name, "view1") ``` -------------------------------- ### Logger.create Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Creates a `LoggerProtocol` instance scoped to a service/name, with optional RUM and trace correlation, console output, and remote sampling controls. ```APIDOC ## Logger.create ### Description Creates a `LoggerProtocol` instance scoped to a service/name, with optional RUM and trace correlation, console output, and remote sampling controls. ### Method `create(with: Logger.Configuration)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import DatadogLogs let logger = Logger.create( with: Logger.Configuration( service: "checkout-service", name: "CheckoutLogger", networkInfoEnabled: true, // attach reachability/carrier info bundleWithRumEnabled: true, // correlate logs with active RUM view bundleWithTraceEnabled: true, // correlate logs with active span remoteSampleRate: 80, // send 80% of logs to Datadog remoteLogThreshold: .warn, // only send warn/error/critical remotely consoleLogFormat: .short // also print to Xcode console ) ) // Severity-specific convenience methods logger.debug("Cart loaded", attributes: ["item_count": 3]) logger.info("Payment initiated", attributes: ["payment_method": "card"]) logger.warn("Retry attempt", attributes: ["attempt": 2]) logger.error("Payment failed", error: paymentError, attributes: ["order_id": "ord-123"]) logger.critical("Database unreachable", error: dbError) // General-purpose log method logger.log(level: .notice, message: "Session started", error: nil, attributes: nil) // Per-logger attribute management logger.addAttribute(forKey: "cart_id", value: "cart-abc") logger.addTag(withKey: "version", value: "3.2.1") logger.removeTag(withKey: "version") logger.removeAttribute(forKey: "cart_id") ``` ### Response None ``` -------------------------------- ### Build SPMProject Source: https://github.com/datadog/dd-sdk-ios/blob/develop/SmokeTests/spm/README.md Run this command after pushing the current branch to the remote to build the SPMProject. ```bash $ make ``` -------------------------------- ### Open SRSnapshotTests Workspace Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogSessionReplay/SRSnapshotTests/README.md Use this command to open the SRSnapshotTests workspace. Ensure the DD_TEST_UTILITIES_ENABLED ENV variable is set for successful compilation. ```bash make sr-snapshot-tests-open ``` -------------------------------- ### Run SwiftLint Linter Source: https://github.com/datadog/dd-sdk-ios/blob/develop/CONTRIBUTING.md Use this command to run the SwiftLint linter with custom rules to ensure code quality. It helps maintain Swift standard syntax across the codebase. ```bash ./tools/lint/run-linter.sh ``` -------------------------------- ### Create and Use a Logger Instance Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Create a Logger instance scoped to a service/name, with options for RUM/trace correlation, console output, and remote sampling. Supports severity-specific methods and per-logger attribute management. ```swift import DatadogLogs let logger = Logger.create( with: Logger.Configuration( service: "checkout-service", name: "CheckoutLogger", networkInfoEnabled: true, // attach reachability/carrier info bundleWithRumEnabled: true, // correlate logs with active RUM view bundleWithTraceEnabled: true, // correlate logs with active span remoteSampleRate: 80, // send 80% of logs to Datadog remoteLogThreshold: .warn, // only send warn/error/critical remotely consoleLogFormat: .short // also print to Xcode console ) ) // Severity-specific convenience methods logger.debug("Cart loaded", attributes: ["item_count": 3]) logger.info("Payment initiated", attributes: ["payment_method": "card"]) logger.warn("Retry attempt", attributes: ["attempt": 2]) logger.error("Payment failed", error: paymentError, attributes: ["order_id": "ord-123"]) logger.critical("Database unreachable", error: dbError) // General-purpose log method logger.log(level: .notice, message: "Session started", error: nil, attributes: nil) // Per-logger attribute management logger.addAttribute(forKey: "cart_id", value: "cart-abc") logger.addTag(withKey: "version", value: "3.2.1") logger.removeTag(withKey: "version") logger.removeAttribute(forKey: "cart_id") ``` -------------------------------- ### WebViewTracking.enable Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Bridges Datadog Browser SDK events (RUM + Logs) from a WKWebView into the native RUM session for unified user journey tracking. ```APIDOC ## WebViewTracking.enable(webView:hosts:) — Hybrid App Web View Tracking Bridges Datadog Browser SDK events (RUM + Logs) from a `WKWebView` into the native RUM session, enabling unified user journey tracking across native and web views. ### Usage ```swift import WebKit import DatadogCore import DatadogWebViewTracking class ViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView(frame: view.bounds) view.addSubview(webView) // Enable bridge — web RUM/Log events will appear in the native session WebViewTracking.enable( webView: webView, hosts: ["example.com", "shop.example.com"], // only bridge events from these hosts logsSampleRate: 50 // sample 50% of web logs ) webView.load(URLRequest(url: URL(string: "https://example.com/checkout")!)) } deinit { // REQUIRED: must be called before webView deallocates WebViewTracking.disable(webView: webView) } } ``` ``` -------------------------------- ### Base64 Encode Configuration File Source: https://github.com/datadog/dd-sdk-ios/blob/develop/E2ETests/README.md Utility command to base64 encode the local configuration file for secure storage in secret variables. ```bash cat E2ETests/xcconfigs/E2E.local.xcconfig | base64 | pbcopy ``` -------------------------------- ### Configure Datadog SDK Source: https://context7.com/datadog/dd-sdk-ios/llms.txt Controls batching behavior, upload frequency, data encryption, proxy settings, and the target Datadog site. Ensure to implement DatadogInternal.DataEncryption if enabling on-disk encryption. ```swift import DatadogCore var config = Datadog.Configuration( clientToken: "pub1234567890abcdef", env: "production", site: .us1, // .us1, .us3, .us5, .eu1, .ap1, .gov service: "com.example.myapp", // defaults to bundle identifier version: "3.2.1", // overrides CFBundleShortVersionString batchSize: .small, // .small | .medium | .large uploadFrequency: .frequent, // .frequent | .average | .rare batchProcessingLevel: .high, // .low | .medium | .high (max batches per cycle) backgroundTasksEnabled: true, // use UIApplication background tasks for uploads proxyConfiguration: [ kCFNetworkProxiesHTTPProxy as AnyHashable: "proxy.example.com", kCFNetworkProxiesHTTPPort as AnyHashable: 8080 ] ) // Enable on-disk encryption config.encryption = MyAESEncryption() // implement DatadogInternal.DataEncryption Datadog.initialize(with: config, trackingConsent: .granted) ``` -------------------------------- ### Test iOS Scheme Source: https://github.com/datadog/dd-sdk-ios/blob/develop/AGENTS.md Run tests for a specific iOS scheme. Replace \"\" with the actual scheme name. ```shell make test-ios SCHEME="" ``` -------------------------------- ### Configure RUM SDK Options Source: https://github.com/datadog/dd-sdk-ios/blob/develop/DatadogRUM/RUM_FEATURE.md Configure options for the Datadog RUM SDK, such as tracking anonymous users, memory warnings, telemetry sampling, and accessibility collection. ```swift trackAnonymousUser: true, // Track memory warnings as RUM errors // Default: true trackMemoryWarnings: true, // SDK telemetry sampling rate (for Datadog internal monitoring) // Default: 20.0 telemetrySampleRate: 20.0, // Collect accessibility settings in view events // Default: false collectAccessibility: false ```