diff --git a/example-new-architecture/App.tsx b/example-new-architecture/App.tsx index e830aa345..be541f17b 100644 --- a/example-new-architecture/App.tsx +++ b/example-new-architecture/App.tsx @@ -6,9 +6,12 @@ import { DdSdkReactNative, DdRum, RumActionType, - DdLogs, DdTrace, } from '@datadog/mobile-react-native'; + +import { + DdLogs +} from '@datadog/mobile-react-native-logs'; import React from 'react'; import type {PropsWithChildren} from 'react'; import { diff --git a/example-new-architecture/ios/Podfile.lock b/example-new-architecture/ios/Podfile.lock index ef249f90a..d14cdc7b3 100644 --- a/example-new-architecture/ios/Podfile.lock +++ b/example-new-architecture/ios/Podfile.lock @@ -1855,7 +1855,7 @@ SPEC CHECKSUMS: DatadogInternal: f98c60cc5b44db688692e2b560ea273182cde022 DatadogLogs: c314b15a97bfc7e0728ea253d3638b0513032d88 DatadogRUM: 6ec371f477a1022fd5aad6ccb5407b85a04db399 - DatadogSDKReactNative: 43f2893d67c3e667792f4ba5ca30411acac12cb5 + DatadogSDKReactNative: 227832d8d4c9af1cb0325f594758e813753c35f0 DatadogTrace: f0de55334db1630938ef980b5e054964652c4606 DatadogWebViewTracking: f637f0e36cf62b713cd6673690d94072e6223570 DoubleConversion: f16ae600a246532c4020132d54af21d0ddb2a385 @@ -1866,62 +1866,62 @@ SPEC CHECKSUMS: hermes-engine: 9e868dc7be781364296d6ee2f56d0c1a9ef0bb11 OpenTelemetrySwiftApi: aaee576ed961e0c348af78df58b61300e95bd104 PLCrashReporter: db59ef96fa3d25f3650040d02ec2798cffee75f2 - RCT-Folly: 7b4f73a92ad9571b9dbdb05bb30fad927fa971e1 + RCT-Folly: ea9d9256ba7f9322ef911169a9f696e5857b9e17 RCTDeprecation: ebe712bb05077934b16c6bf25228bdec34b64f83 RCTRequired: ca91e5dd26b64f577b528044c962baf171c6b716 RCTTypeSafety: e7678bd60850ca5a41df9b8dc7154638cb66871f React: 4641770499c39f45d4e7cde1eba30e081f9d8a3d React-callinvoker: 4bef67b5c7f3f68db5929ab6a4d44b8a002998ea - React-Core: 0a06707a0b34982efc4a556aff5dae4b22863455 - React-CoreModules: 907334e94314189c2e5eed4877f3efe7b26d85b0 - React-cxxreact: 3a1d5e8f4faa5e09be26614e9c8bbcae8d11b73d + React-Core: a68cea3e762814e60ecc3fa521c7f14c36c99245 + React-CoreModules: d81b1eaf8066add66299bab9d23c9f00c9484c7c + React-cxxreact: 984f8b1feeca37181d4e95301fcd6f5f6501c6ab React-debug: 817160c07dc8d24d020fbd1eac7b3558ffc08964 - React-defaultsnativemodule: 814830ccbc3fb08d67d0190e63b179ee4098c67b - React-domnativemodule: 270acf94bd0960b026bc3bfb327e703665d27fb4 - React-Fabric: 64586dc191fc1c170372a638b8e722e4f1d0a09b - React-FabricComponents: b0ebd032387468ea700574c581b139f57a7497fb - React-FabricImage: 81f0e0794caf25ad1224fa406d288fbc1986607f + React-defaultsnativemodule: 18a684542f82ce1897552a1c4b847be414c9566e + React-domnativemodule: 90bdd4ec3ab38c47cfc3461c1e9283a8507d613f + React-Fabric: f6dade7007533daeb785ba5925039d83f343be4b + React-FabricComponents: b0655cc3e1b5ae12a4a1119aa7d8308f0ad33520 + React-FabricImage: 9b157c4c01ac2bf433f834f0e1e5fe234113a576 React-featureflags: f2792b067a351d86fdc7bec23db3b9a2f2c8d26c - React-featureflagsnativemodule: 0d7091ae344d6160c0557048e127897654a5c00f - React-graphics: cbebe910e4a15b65b0bff94a4d3ed278894d6386 - React-hermes: ec18c10f5a69d49fb9b5e17ae95494e9ea13d4d3 - React-idlecallbacksnativemodule: 6b84add48971da9c40403bd1860d4896462590f2 - React-ImageManager: f2a4c01c2ccb2193e60a20c135da74c7ca4d36f2 - React-jserrorhandler: 61d205b5a7cbc57fed3371dd7eed48c97f49fc64 - React-jsi: 95f7676103137861b79b0f319467627bcfa629ee - React-jsiexecutor: 41e0fe87cda9ea3970ffb872ef10f1ff8dbd1932 - React-jsinspector: 15578208796723e5c6f39069b6e8bf36863ef6e2 - React-jsitracing: 3758cdb155ea7711f0e77952572ea62d90c69f0b - React-logger: dbca7bdfd4aa5ef69431362bde6b36d49403cb20 - React-Mapbuffer: 6efad4a606c1fae7e4a93385ee096681ef0300dc - React-microtasksnativemodule: a645237a841d733861c70b69908ab4a1707b52ad + React-featureflagsnativemodule: 742a8325b3c821d2a1ca13a6d2a0fc72d04555e0 + React-graphics: 68969e4e49d73f89da7abef4116c9b5f466aa121 + React-hermes: ac0bcba26a5d288ebc99b500e1097da2d0297ddf + React-idlecallbacksnativemodule: d61d9c9816131bf70d3d80cd04889fc625ee523f + React-ImageManager: e906eec93a9eb6102a06576b89d48d80a4683020 + React-jserrorhandler: ac5dde01104ff444e043cad8f574ca02756e20d6 + React-jsi: 496fa2b9d63b726aeb07d0ac800064617d71211d + React-jsiexecutor: dd22ab48371b80f37a0a30d0e8915b6d0f43a893 + React-jsinspector: 4629ac376f5765e684d19064f2093e55c97fd086 + React-jsitracing: 7a1c9cd484248870cf660733cd3b8114d54c035f + React-logger: c4052eb941cca9a097ef01b59543a656dc088559 + React-Mapbuffer: 33546a3ebefbccb8770c33a1f8a5554fa96a54de + React-microtasksnativemodule: d80ff86c8902872d397d9622f1a97aadcc12cead React-nativeconfig: 8efdb1ef1e9158c77098a93085438f7e7b463678 - React-NativeModulesApple: 958d4f6c5c2ace4c0f427cf7ef82e28ae6538a22 - React-perflogger: 9b4f13c0afe56bc7b4a0e93ec74b1150421ee22d - React-performancetimeline: 359db1cb889aa0282fafc5838331b0987c4915a9 + React-NativeModulesApple: cebca2e5320a3d66e123cade23bd90a167ffce5e + React-perflogger: 72e653eb3aba9122f9e57cf012d22d2486f33358 + React-performancetimeline: cd6a9374a72001165995d2ab632f672df04076dc React-RCTActionSheet: aacf2375084dea6e7c221f4a727e579f732ff342 - React-RCTAnimation: d8c82deebebe3aaf7a843affac1b57cb2dc073d4 - React-RCTAppDelegate: 1774aa421a29a41a704ecaf789811ef73c4634b6 - React-RCTBlob: 70a58c11a6a3500d1a12f2e51ca4f6c99babcff8 - React-RCTFabric: 731cda82aed592aacce2d32ead69d78cde5d9274 - React-RCTImage: 5e9d655ba6a790c31e3176016f9b47fd0978fbf0 - React-RCTLinking: 2a48338252805091f7521eaf92687206401bdf2a - React-RCTNetwork: 0c1282b377257f6b1c81934f72d8a1d0c010e4c3 - React-RCTSettings: f757b679a74e5962be64ea08d7865a7debd67b40 - React-RCTText: e7d20c490b407d3b4a2daa48db4bcd8ec1032af2 - React-RCTVibration: 8228e37144ca3122a91f1de16ba8e0707159cfec + React-RCTAnimation: 395ab53fd064dff81507c15efb781c8684d9a585 + React-RCTAppDelegate: 345a6f1b82abc578437df0ce7e9c48740eca827c + React-RCTBlob: 13311e554c1a367de063c10ee7c5e6573b2dd1d6 + React-RCTFabric: 007b1a98201cc49b5bc6e1417d7fe3f6fc6e2b78 + React-RCTImage: 1b1f914bcc12187c49ba5d949dac38c2eb9f5cc8 + React-RCTLinking: 4ac7c42beb65e36fba0376f3498f3cd8dd0be7fa + React-RCTNetwork: 938902773add4381e84426a7aa17a2414f5f94f7 + React-RCTSettings: e848f1ba17a7a18479cf5a31d28145f567da8223 + React-RCTText: 7e98fafdde7d29e888b80f0b35544e0cb07913cf + React-RCTVibration: cd7d80affd97dc7afa62f9acd491419558b64b78 React-rendererconsistency: b4917053ecbaa91469c67a4319701c9dc0d40be6 - React-rendererdebug: 81becbc8852b38d9b1b68672aa504556481330d5 + React-rendererdebug: aa181c36dd6cf5b35511d1ed875d6638fd38f0ec React-rncore: 120d21715c9b4ba8f798bffe986cb769b988dd74 - React-RuntimeApple: 52ed0e9e84a7c2607a901149fb13599a3c057655 - React-RuntimeCore: ca6189d2e53d86db826e2673fe8af6571b8be157 + React-RuntimeApple: d033becbbd1eba6f9f6e3af6f1893030ce203edd + React-RuntimeCore: 38af280bb678e66ba000a3c3d42920b2a138eebb React-runtimeexecutor: 877596f82f5632d073e121cba2d2084b76a76899 - React-RuntimeHermes: 3b752dc5d8a1661c9d1687391d6d96acfa385549 - React-runtimescheduler: 8321bb09175ace2a4f0b3e3834637eb85bf42ebe + React-RuntimeHermes: 37aad735ff21ca6de2d8450a96de1afe9f86c385 + React-runtimescheduler: 8ec34cc885281a34696ea16c4fd86892d631f38d React-timing: 331cbf9f2668c67faddfd2e46bb7f41cbd9320b9 - React-utils: 54df9ada708578c8ad40d92895d6fed03e0e8a9e - ReactCodegen: 21a52ccddc6479448fc91903a437dd23ddc7366c - ReactCommon: bfd3600989d79bc3acbe7704161b171a1480b9fd + React-utils: ed818f19ab445000d6b5c4efa9d462449326cc9f + ReactCodegen: f853a20cc9125c5521c8766b4b49375fec20648b + ReactCommon: 300d8d9c5cb1a6cd79a67cf5d8f91e4d477195f9 SocketRocket: d4aabe649be1e368d1318fdf28a022d714d65748 Yoga: feb4910aba9742cfedc059e2b2902e22ffe9954a diff --git a/example-new-architecture/package.json b/example-new-architecture/package.json index 92f2a7640..a3495bc12 100644 --- a/example-new-architecture/package.json +++ b/example-new-architecture/package.json @@ -9,6 +9,7 @@ }, "dependencies": { "@datadog/mobile-react-native": "workspace:packages/core", + "@datadog/mobile-react-native-logs": "workspace:packages/logs", "react": "18.3.1", "react-native": "0.76.9" }, diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index aef22ad73..518a87257 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -107,6 +107,8 @@ dependencies { implementation jscFlavor } + implementation project(":datadog_mobile-react-native-logs") + constraints { implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0") { because("kotlin-stdlib-jdk7 is now a part of kotlin-stdlib") diff --git a/example/android/app/src/main/java/com/ddsdkreactnativeexample/MainApplication.kt b/example/android/app/src/main/java/com/ddsdkreactnativeexample/MainApplication.kt index 9efdf4b7b..97c38c1cb 100644 --- a/example/android/app/src/main/java/com/ddsdkreactnativeexample/MainApplication.kt +++ b/example/android/app/src/main/java/com/ddsdkreactnativeexample/MainApplication.kt @@ -15,7 +15,7 @@ import com.reactnativenavigation.NavigationApplication import com.reactnativenavigation.react.NavigationReactNativeHost import com.facebook.react.soloader.OpenSourceMergedSoMapping import com.facebook.soloader.SoLoader - +import com.datadog.reactnative.logs.DdSdkReactNativeLogsPackage; class MainApplication : NavigationApplication() { @@ -36,6 +36,7 @@ class MainApplication : NavigationApplication() { val packages = PackageList(this).packages // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()) + packages.add(DdSdkReactNativeLogsPackage()) return packages } diff --git a/example/android/settings.gradle b/example/android/settings.gradle index 940fd0070..4f7221523 100644 --- a/example/android/settings.gradle +++ b/example/android/settings.gradle @@ -5,6 +5,9 @@ rootProject.name = 'DdSdkReactNativeExample' include ':app' includeBuild('../node_modules/@react-native/gradle-plugin') +include(":datadog_mobile-react-native-logs") +project(":datadog_mobile-react-native-logs").projectDir = new File(rootProject.projectDir, "../../packages/logs/android") + diff --git a/example/app.json b/example/app.json index f0f0c83d7..70b08eb89 100644 --- a/example/app.json +++ b/example/app.json @@ -1,5 +1,5 @@ { "name": "DdSdkReactNativeExample", "displayName": "DD RN Sample", - "navigation": "react-native-navigation" + "navigation": "react-navigation" } diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 31b1ad3fd..3fd46a319 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -26,6 +26,31 @@ PODS: - DatadogTrace (= 2.29.0) - DatadogWebViewTracking (= 2.29.0) - React-Core + - DatadogSDKReactNativeLogs (2.11.0): + - DatadogCore (= 2.29.0) + - DatadogInternal (= 2.29.0) + - DatadogLogs (= 2.29.0) + - DatadogSDKReactNative + - DoubleConversion + - glog + - hermes-engine + - RCT-Folly (= 2024.10.14.00) + - RCTRequired + - RCTTypeSafety + - React-Core + - React-debug + - React-Fabric + - React-featureflags + - React-graphics + - React-ImageManager + - React-NativeModulesApple + - React-RCTFabric + - React-rendererdebug + - React-utils + - ReactCodegen + - ReactCommon/turbomodule/bridging + - ReactCommon/turbomodule/core + - Yoga - DatadogSDKReactNativeSessionReplay (2.10.1): - DatadogSDKReactNative - DatadogSessionReplay (= 2.29.0) @@ -1743,6 +1768,7 @@ DEPENDENCIES: - boost (from `../node_modules/react-native/third-party-podspecs/boost.podspec`) - DatadogSDKReactNative (from `../../packages/core/DatadogSDKReactNative.podspec`) - DatadogSDKReactNative/Tests (from `../../packages/core/DatadogSDKReactNative.podspec`) + - "DatadogSDKReactNativeLogs (from `../node_modules/@datadog/mobile-react-native-logs`)" - DatadogSDKReactNativeSessionReplay (from `../../packages/react-native-session-replay/DatadogSDKReactNativeSessionReplay.podspec`) - DatadogSDKReactNativeSessionReplay/Tests (from `../../packages/react-native-session-replay/DatadogSDKReactNativeSessionReplay.podspec`) - DatadogSDKReactNativeWebView (from `../../packages/react-native-webview/DatadogSDKReactNativeWebView.podspec`) @@ -1840,6 +1866,8 @@ EXTERNAL SOURCES: :podspec: "../node_modules/react-native/third-party-podspecs/boost.podspec" DatadogSDKReactNative: :path: "../../packages/core/DatadogSDKReactNative.podspec" + DatadogSDKReactNativeLogs: + :path: "../node_modules/@datadog/mobile-react-native-logs" DatadogSDKReactNativeSessionReplay: :path: "../../packages/react-native-session-replay/DatadogSDKReactNativeSessionReplay.podspec" DatadogSDKReactNativeWebView: @@ -1993,9 +2021,10 @@ SPEC CHECKSUMS: DatadogInternal: f98c60cc5b44db688692e2b560ea273182cde022 DatadogLogs: c314b15a97bfc7e0728ea253d3638b0513032d88 DatadogRUM: 6ec371f477a1022fd5aad6ccb5407b85a04db399 - DatadogSDKReactNative: 6bcecc6492aa0cbbe77a4eea9ab2056ec53ad0d3 - DatadogSDKReactNativeSessionReplay: 89475adadb47b2e7f18f9f5f2a82793cc9471fcd - DatadogSDKReactNativeWebView: 5369bb452fb77e4a7de3efc8fb7307a5bf17c73e + DatadogSDKReactNative: 81f50b5238dcf7732ebca0151d4e6d5555121b1b + DatadogSDKReactNativeLogs: 5c653dbc15a5c3f0357ffb1f952ae53cfa494bab + DatadogSDKReactNativeSessionReplay: 207aba83107a37ed08162790aa27a449a486addd + DatadogSDKReactNativeWebView: ac2d200b50ce67146a86ed84883667a4ab270d15 DatadogSessionReplay: 1f2f70afa2fc5870ce7304a02749f73529d3e6cb DatadogTrace: f0de55334db1630938ef980b5e054964652c4606 DatadogWebViewTracking: f637f0e36cf62b713cd6673690d94072e6223570 @@ -2008,69 +2037,69 @@ SPEC CHECKSUMS: HMSegmentedControl: 34c1f54d822d8308e7b24f5d901ec674dfa31352 OpenTelemetrySwiftApi: aaee576ed961e0c348af78df58b61300e95bd104 PLCrashReporter: db59ef96fa3d25f3650040d02ec2798cffee75f2 - RCT-Folly: 7b4f73a92ad9571b9dbdb05bb30fad927fa971e1 + RCT-Folly: ea9d9256ba7f9322ef911169a9f696e5857b9e17 RCTDeprecation: ebe712bb05077934b16c6bf25228bdec34b64f83 RCTRequired: ca91e5dd26b64f577b528044c962baf171c6b716 RCTTypeSafety: e7678bd60850ca5a41df9b8dc7154638cb66871f React: 4641770499c39f45d4e7cde1eba30e081f9d8a3d React-callinvoker: 4bef67b5c7f3f68db5929ab6a4d44b8a002998ea - React-Core: 0a06707a0b34982efc4a556aff5dae4b22863455 - React-CoreModules: 907334e94314189c2e5eed4877f3efe7b26d85b0 - React-cxxreact: 3a1d5e8f4faa5e09be26614e9c8bbcae8d11b73d + React-Core: a68cea3e762814e60ecc3fa521c7f14c36c99245 + React-CoreModules: d81b1eaf8066add66299bab9d23c9f00c9484c7c + React-cxxreact: 984f8b1feeca37181d4e95301fcd6f5f6501c6ab React-debug: 817160c07dc8d24d020fbd1eac7b3558ffc08964 - React-defaultsnativemodule: a965cb39fb0a79276ab611793d39f52e59a9a851 - React-domnativemodule: d647f94e503c62c44f54291334b1aa22a30fa08b - React-Fabric: 64586dc191fc1c170372a638b8e722e4f1d0a09b - React-FabricComponents: b0ebd032387468ea700574c581b139f57a7497fb - React-FabricImage: 81f0e0794caf25ad1224fa406d288fbc1986607f + React-defaultsnativemodule: 21f216e8db975897eb32b5f13247f5bbfaa97f41 + React-domnativemodule: 19270ad4b8d33312838d257f24731a0026809d49 + React-Fabric: f6dade7007533daeb785ba5925039d83f343be4b + React-FabricComponents: b0655cc3e1b5ae12a4a1119aa7d8308f0ad33520 + React-FabricImage: 9b157c4c01ac2bf433f834f0e1e5fe234113a576 React-featureflags: f2792b067a351d86fdc7bec23db3b9a2f2c8d26c - React-featureflagsnativemodule: 95a02d895475de8ace78fedd76143866838bb720 - React-graphics: cbebe910e4a15b65b0bff94a4d3ed278894d6386 - React-hermes: ec18c10f5a69d49fb9b5e17ae95494e9ea13d4d3 - React-idlecallbacksnativemodule: 0c1ae840cc5587197cd926a3cb76828ad059d116 - React-ImageManager: f2a4c01c2ccb2193e60a20c135da74c7ca4d36f2 - React-jserrorhandler: 61d205b5a7cbc57fed3371dd7eed48c97f49fc64 - React-jsi: 95f7676103137861b79b0f319467627bcfa629ee - React-jsiexecutor: 41e0fe87cda9ea3970ffb872ef10f1ff8dbd1932 - React-jsinspector: 15578208796723e5c6f39069b6e8bf36863ef6e2 - React-jsitracing: 3758cdb155ea7711f0e77952572ea62d90c69f0b - React-logger: dbca7bdfd4aa5ef69431362bde6b36d49403cb20 - React-Mapbuffer: 6efad4a606c1fae7e4a93385ee096681ef0300dc - React-microtasksnativemodule: 8732b71aa66045da4bb341ddee1bb539f71e5f38 - react-native-crash-tester: 3ffaa64141427ca362079cb53559fe9a532487ae - react-native-safe-area-context: 04803a01f39f31cc6605a5531280b477b48f8a88 - react-native-webview: 1e12de2fad74c17b4f8b1b53ebd1e3baa0148d71 + React-featureflagsnativemodule: 3a8731d8fd9f755be57e00d9fa8a7f92aa77e87d + React-graphics: 68969e4e49d73f89da7abef4116c9b5f466aa121 + React-hermes: ac0bcba26a5d288ebc99b500e1097da2d0297ddf + React-idlecallbacksnativemodule: 9a2c5b5c174c0c476f039bedc1b9497a8272133e + React-ImageManager: e906eec93a9eb6102a06576b89d48d80a4683020 + React-jserrorhandler: ac5dde01104ff444e043cad8f574ca02756e20d6 + React-jsi: 496fa2b9d63b726aeb07d0ac800064617d71211d + React-jsiexecutor: dd22ab48371b80f37a0a30d0e8915b6d0f43a893 + React-jsinspector: 4629ac376f5765e684d19064f2093e55c97fd086 + React-jsitracing: 7a1c9cd484248870cf660733cd3b8114d54c035f + React-logger: c4052eb941cca9a097ef01b59543a656dc088559 + React-Mapbuffer: 33546a3ebefbccb8770c33a1f8a5554fa96a54de + React-microtasksnativemodule: 5c3d795318c22ab8df55100e50b151384a4a60b3 + react-native-crash-tester: 48bde9d6f5256c61ef2e0c52dfc74256b26e55eb + react-native-safe-area-context: e134b241010ebe2aacdcea013565963d13826faa + react-native-webview: 2ea635bc43fd8a4b89de61133e8cc0607084e9f8 React-nativeconfig: 8efdb1ef1e9158c77098a93085438f7e7b463678 - React-NativeModulesApple: 958d4f6c5c2ace4c0f427cf7ef82e28ae6538a22 - React-perflogger: 9b4f13c0afe56bc7b4a0e93ec74b1150421ee22d - React-performancetimeline: 359db1cb889aa0282fafc5838331b0987c4915a9 + React-NativeModulesApple: cebca2e5320a3d66e123cade23bd90a167ffce5e + React-perflogger: 72e653eb3aba9122f9e57cf012d22d2486f33358 + React-performancetimeline: cd6a9374a72001165995d2ab632f672df04076dc React-RCTActionSheet: aacf2375084dea6e7c221f4a727e579f732ff342 - React-RCTAnimation: d8c82deebebe3aaf7a843affac1b57cb2dc073d4 - React-RCTAppDelegate: 6c0377d9c4058773ea7073bb34bb9ebd6ddf5a84 - React-RCTBlob: 70a58c11a6a3500d1a12f2e51ca4f6c99babcff8 - React-RCTFabric: 7eb6dd2c8fda98cb860a572e3f4e4eb60d62c89e - React-RCTImage: 5e9d655ba6a790c31e3176016f9b47fd0978fbf0 - React-RCTLinking: 2a48338252805091f7521eaf92687206401bdf2a - React-RCTNetwork: 0c1282b377257f6b1c81934f72d8a1d0c010e4c3 - React-RCTSettings: f757b679a74e5962be64ea08d7865a7debd67b40 - React-RCTText: e7d20c490b407d3b4a2daa48db4bcd8ec1032af2 - React-RCTVibration: 8228e37144ca3122a91f1de16ba8e0707159cfec + React-RCTAnimation: 395ab53fd064dff81507c15efb781c8684d9a585 + React-RCTAppDelegate: 1e5b43833e3e36e9fa34eec20be98174bc0e14a2 + React-RCTBlob: 13311e554c1a367de063c10ee7c5e6573b2dd1d6 + React-RCTFabric: bd906861a4e971e21d8df496c2d8f3ca6956f840 + React-RCTImage: 1b1f914bcc12187c49ba5d949dac38c2eb9f5cc8 + React-RCTLinking: 4ac7c42beb65e36fba0376f3498f3cd8dd0be7fa + React-RCTNetwork: 938902773add4381e84426a7aa17a2414f5f94f7 + React-RCTSettings: e848f1ba17a7a18479cf5a31d28145f567da8223 + React-RCTText: 7e98fafdde7d29e888b80f0b35544e0cb07913cf + React-RCTVibration: cd7d80affd97dc7afa62f9acd491419558b64b78 React-rendererconsistency: b4917053ecbaa91469c67a4319701c9dc0d40be6 - React-rendererdebug: 81becbc8852b38d9b1b68672aa504556481330d5 + React-rendererdebug: aa181c36dd6cf5b35511d1ed875d6638fd38f0ec React-rncore: 120d21715c9b4ba8f798bffe986cb769b988dd74 - React-RuntimeApple: 52ed0e9e84a7c2607a901149fb13599a3c057655 - React-RuntimeCore: ca6189d2e53d86db826e2673fe8af6571b8be157 + React-RuntimeApple: d033becbbd1eba6f9f6e3af6f1893030ce203edd + React-RuntimeCore: 38af280bb678e66ba000a3c3d42920b2a138eebb React-runtimeexecutor: 877596f82f5632d073e121cba2d2084b76a76899 - React-RuntimeHermes: 3b752dc5d8a1661c9d1687391d6d96acfa385549 - React-runtimescheduler: 8321bb09175ace2a4f0b3e3834637eb85bf42ebe + React-RuntimeHermes: 37aad735ff21ca6de2d8450a96de1afe9f86c385 + React-runtimescheduler: 8ec34cc885281a34696ea16c4fd86892d631f38d React-timing: 331cbf9f2668c67faddfd2e46bb7f41cbd9320b9 - React-utils: 54df9ada708578c8ad40d92895d6fed03e0e8a9e - ReactCodegen: 21a52ccddc6479448fc91903a437dd23ddc7366c - ReactCommon: bfd3600989d79bc3acbe7704161b171a1480b9fd - ReactNativeNavigation: 50c1eef68b821e7265eff3a391d27ed18fdce459 - RNCAsyncStorage: 23e56519cc41d3bade3c8d4479f7760cb1c11996 - RNGestureHandler: 950dfa674dbf481460ca389c65b9036ac4ab8ada - RNScreens: 606ab1cf68162f7ba0d049a31f2a84089a6fffb4 + React-utils: ed818f19ab445000d6b5c4efa9d462449326cc9f + ReactCodegen: f853a20cc9125c5521c8766b4b49375fec20648b + ReactCommon: 300d8d9c5cb1a6cd79a67cf5d8f91e4d477195f9 + ReactNativeNavigation: 445f86273eb245d15b14023ee4ef9d6e4f891ad6 + RNCAsyncStorage: b44e8a4e798c3e1f56bffccd0f591f674fb9198f + RNGestureHandler: cb711d56ee3b03a5adea1d38324d4459ab55653f + RNScreens: f75b26fd4777848c216e27b0a09e1bf9c9f4760a SocketRocket: d4aabe649be1e368d1318fdf28a022d714d65748 Yoga: feb4910aba9742cfedc059e2b2902e22ffe9954a diff --git a/example/package.json b/example/package.json index 8232a359f..403fdd095 100644 --- a/example/package.json +++ b/example/package.json @@ -11,6 +11,7 @@ }, "dependencies": { "@datadog/mobile-react-native": "workspace:packages/core", + "@datadog/mobile-react-native-logs": "workspace:packages/logs", "@datadog/mobile-react-native-navigation": "workspace:packages/react-native-navigation", "@datadog/mobile-react-native-session-replay": "workspace:packages/react-native-session-replay", "@datadog/mobile-react-native-webview": "workspace:packages/react-native-webview", diff --git a/example/src/ddUtils.tsx b/example/src/ddUtils.tsx index 2cd64d477..7d9469910 100644 --- a/example/src/ddUtils.tsx +++ b/example/src/ddUtils.tsx @@ -1,12 +1,15 @@ import { DatadogProviderConfiguration, - DdLogs, DdSdkReactNative, DdSdkReactNativeConfiguration, SdkVerbosity, TrackingConsent } from '@datadog/mobile-react-native'; +import { + DdLogs, +} from '@datadog/mobile-react-native-logs'; + import {APPLICATION_ID, CLIENT_TOKEN, ENVIRONMENT} from './ddCredentials'; // New SDK Setup - not available for react-native-navigation @@ -28,10 +31,28 @@ export function getDatadogConfig(trackingConsent: TrackingConsent) { return config } - export function onDatadogInitialization() { - DdLogs.info('The RN Sdk was properly initialized') - DdSdkReactNative.setUserInfo({id: "1337", name: "Xavier", email: "xg@example.com", extraInfo: { type: "premium" } }) - DdSdkReactNative.setAttributes({campaign: "ad-network"}) + export async function onDatadogInitialization() { + + try { + await DdLogs.enable({}); + DdLogs.debug('DDLogs was initialized'); + DdSdkReactNative.setUserInfo({id: "w00t", name: "Sergio", email: "modular@sdk.com", extraInfo: { type: "premium" } }) + setTimeout(async () => { + await DdLogs.enable({ + customEndpoints: { + logs: "custom.endpoint" + } + }); + DdLogs.debug('DDLogs was initialized again with a custom endpoint'); + + setTimeout(async () => { + await DdLogs.enable({}); + DdLogs.debug('DDLogs was initialized for the third time'); + }, 5000); + }, 5000); + } catch (error) { + console.log("ERROR during init", error); + } } // Legacy SDK Setup diff --git a/example/src/screens/MainScreen.tsx b/example/src/screens/MainScreen.tsx index 7f0fbdec2..0f44e8315 100644 --- a/example/src/screens/MainScreen.tsx +++ b/example/src/screens/MainScreen.tsx @@ -94,7 +94,6 @@ export default class MainScreen extends Component { componentDidMount() { this.updateTrackingConsent() - DdLogs.debug("[DATADOG SDK] Test React Native Debug Log"); } updateTrackingConsent() { diff --git a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DatadogSDKWrapper.kt b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DatadogSDKWrapper.kt index 7452c40ef..c9159e42b 100644 --- a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DatadogSDKWrapper.kt +++ b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DatadogSDKWrapper.kt @@ -72,7 +72,7 @@ object DatadogSDKWrapperStorage { } } -internal class DatadogSDKWrapper : DatadogWrapper { +class DatadogSDKWrapper : DatadogWrapper { override var bundleLogsWithRum = DefaultConfiguration.bundleLogsWithRum override var bundleLogsWithTraces = DefaultConfiguration.bundleLogsWithTraces @@ -116,10 +116,6 @@ internal class DatadogSDKWrapper : DatadogWrapper { Rum.enable(configuration, DatadogSDKWrapperStorage.getSdkCore()) } - override fun enableLogs(configuration: LogsConfiguration) { - Logs.enable(configuration, DatadogSDKWrapperStorage.getSdkCore()) - } - override fun enableTrace(configuration: TraceConfiguration) { Trace.enable(configuration, DatadogSDKWrapperStorage.getSdkCore()) } diff --git a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DatadogWrapper.kt b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DatadogWrapper.kt index 41e86f4d5..5348b8272 100644 --- a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DatadogWrapper.kt +++ b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DatadogWrapper.kt @@ -73,15 +73,6 @@ interface DatadogWrapper { configuration: RumConfiguration ) - /** - * Enables the Logs feature of the SDK. - * - * @param configuration the configuration for the Logs feature - */ - fun enableLogs( - configuration: LogsConfiguration - ) - /** * Enables the Trace feature of the SDK. * diff --git a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkConfigurationExt.kt b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkConfigurationExt.kt index bcffdbbf5..a08060a0b 100644 --- a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkConfigurationExt.kt +++ b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkConfigurationExt.kt @@ -9,6 +9,7 @@ package com.datadog.reactnative import android.util.Log +import com.datadog.android.log.LogsConfiguration import com.datadog.android.trace.TracingHeaderType import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap @@ -64,7 +65,7 @@ internal fun ReadableMap.asConfigurationForTelemetry(): ConfigurationForTelemetr ) } -internal fun ReadableMap.asCustomEndpoints(): CustomEndpoints { +fun ReadableMap.asCustomEndpoints(): CustomEndpoints { return CustomEndpoints( rum = getString("rum"), logs = getString("logs"), diff --git a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkNativeInitialization.kt b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkNativeInitialization.kt index 67450add7..68b41bd2d 100644 --- a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkNativeInitialization.kt +++ b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkNativeInitialization.kt @@ -42,7 +42,6 @@ class DdSdkNativeInitialization internal constructor( internal fun initialize(ddSdkConfiguration: DdSdkConfiguration) { val sdkConfiguration = buildSdkConfiguration(ddSdkConfiguration) val rumConfiguration = buildRumConfiguration(ddSdkConfiguration) - val logsConfiguration = buildLogsConfiguration(ddSdkConfiguration) val traceConfiguration = buildTraceConfiguration(ddSdkConfiguration) val trackingConsent = buildTrackingConsent(ddSdkConfiguration.trackingConsent) @@ -63,7 +62,8 @@ class DdSdkNativeInitialization internal constructor( datadog.enableTrace(traceConfiguration) - datadog.enableLogs(logsConfiguration) + // REMOVED FOR TEST + // datadog.enableLogs(logsConfiguration) } private fun configureRumAndTracesForLogs(configuration: DdSdkConfiguration) { @@ -223,15 +223,6 @@ class DdSdkNativeInitialization internal constructor( return configBuilder.build() } - private fun buildLogsConfiguration(configuration: DdSdkConfiguration): LogsConfiguration { - val configBuilder = LogsConfiguration.Builder() - configuration.customEndpoints?.logs?.let { - configBuilder.useCustomEndpoint(it) - } - - return configBuilder.build() - } - private fun buildTraceConfiguration(configuration: DdSdkConfiguration): TraceConfiguration { val configBuilder = TraceConfiguration.Builder() configuration.customEndpoints?.trace?.let { diff --git a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkReactNativePackage.kt b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkReactNativePackage.kt index bac9f49f5..adf896c0d 100644 --- a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkReactNativePackage.kt +++ b/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdSdkReactNativePackage.kt @@ -23,7 +23,6 @@ class DdSdkReactNativePackage : TurboReactPackage() { DdSdkImplementation.NAME -> DdSdk(reactContext, sdkWrapper) DdRumImplementation.NAME -> DdRum(reactContext, sdkWrapper) DdTraceImplementation.NAME -> DdTrace(reactContext) - DdLogsImplementation.NAME -> DdLogs(reactContext, sdkWrapper) else -> null } } @@ -35,7 +34,6 @@ class DdSdkReactNativePackage : TurboReactPackage() { DdSdkImplementation.NAME, DdRumImplementation.NAME, DdTraceImplementation.NAME, - DdLogsImplementation.NAME ).associateWith { ReactModuleInfo( it, diff --git a/packages/core/android/src/main/kotlin/com/datadog/reactnative/GlobalState.kt b/packages/core/android/src/main/kotlin/com/datadog/reactnative/GlobalState.kt index e93bb0bea..9fa67a0ba 100644 --- a/packages/core/android/src/main/kotlin/com/datadog/reactnative/GlobalState.kt +++ b/packages/core/android/src/main/kotlin/com/datadog/reactnative/GlobalState.kt @@ -2,10 +2,10 @@ package com.datadog.reactnative import java.util.concurrent.ConcurrentHashMap -internal object GlobalState { +object GlobalState { // Keeps a record of global attributes for logs / spans - internal val globalAttributes: MutableMap = ConcurrentHashMap() + val globalAttributes: MutableMap = ConcurrentHashMap() /** * Adds a global attribute to all future RUM events. diff --git a/packages/core/android/src/test/kotlin/com/datadog/reactnative/DdLogsTest.kt b/packages/core/android/src/test/kotlin/com/datadog/reactnative/DdLogsTest.kt deleted file mode 100644 index 671bd0503..000000000 --- a/packages/core/android/src/test/kotlin/com/datadog/reactnative/DdLogsTest.kt +++ /dev/null @@ -1,400 +0,0 @@ -/* - * 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 2016-Present Datadog, Inc. - */ - -package com.datadog.reactnative - -import android.util.Log -import com.datadog.android.log.Logger -import com.datadog.tools.unit.GenericAssert.Companion.assertThat -import com.facebook.react.bridge.Promise -import com.facebook.react.bridge.ReadableMap -import fr.xgouchet.elmyr.Forge -import fr.xgouchet.elmyr.annotation.AdvancedForgery -import fr.xgouchet.elmyr.annotation.MapForgery -import fr.xgouchet.elmyr.annotation.StringForgery -import fr.xgouchet.elmyr.annotation.StringForgeryType -import fr.xgouchet.elmyr.junit5.ForgeExtension -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import org.junit.jupiter.api.extension.Extensions -import org.mockito.Mock -import org.mockito.junit.jupiter.MockitoExtension -import org.mockito.junit.jupiter.MockitoSettings -import org.mockito.kotlin.argumentCaptor -import org.mockito.kotlin.doReturn -import org.mockito.kotlin.times -import org.mockito.kotlin.verify -import org.mockito.kotlin.verifyNoInteractions -import org.mockito.kotlin.whenever -import org.mockito.quality.Strictness - -@Extensions( - ExtendWith(MockitoExtension::class), - ExtendWith(ForgeExtension::class) -) -@MockitoSettings(strictness = Strictness.LENIENT) -internal class DdLogsTest { - - lateinit var testedLogs: DdLogsImplementation - - @Mock - lateinit var mockLogger: Logger - - @StringForgery - lateinit var fakeMessage: String - - private var fakeErrorKind: String? = null - - private var fakeErrorMessage: String? = null - - private var fakeStacktrace: String? = null - - @Mock - lateinit var mockPromise: Promise - - @Mock - lateinit var mockDatadog: DatadogWrapper - - @Mock - lateinit var mockContext: ReadableMap - - @MapForgery( - key = AdvancedForgery(string = [StringForgery()]), - value = AdvancedForgery(string = [StringForgery(StringForgeryType.HEXADECIMAL)]) - ) - lateinit var fakeGlobalState: Map - - @BeforeEach - fun `set up`(forge: Forge) { - whenever(mockDatadog.isInitialized()) doReturn true - testedLogs = DdLogsImplementation(mockLogger, mockDatadog) - fakeErrorKind = forge.aNullable { forge.aString() } - fakeErrorMessage = forge.aNullable { forge.aString() } - fakeStacktrace = forge.aNullable { forge.aString() } - } - - @AfterEach - fun `tear down`() { - GlobalState.globalAttributes.clear() - } - - @Test - fun `M forward debug log W debug()`() { - // When - testedLogs.debug(fakeMessage, mockContext, mockPromise) - - // Then - verify(mockLogger).d(fakeMessage, attributes = mockContext.toHashMap()) - } - - @Test - fun `M forward info log W info()`() { - // When - testedLogs.info(fakeMessage, mockContext, mockPromise) - - // Then - verify(mockLogger).i(fakeMessage, attributes = mockContext.toHashMap()) - } - - @Test - fun `M forward warning log W warn()`() { - // When - testedLogs.warn(fakeMessage, mockContext, mockPromise) - - // Then - verify(mockLogger).w(fakeMessage, attributes = mockContext.toHashMap()) - } - - @Test - fun `M forward error log W error()`() { - // When - testedLogs.error(fakeMessage, mockContext, mockPromise) - - // Then - verify(mockLogger).e(fakeMessage, attributes = mockContext.toHashMap()) - } - - @Test - fun `M forward debug log with global state W debug()`() { - // Given - fakeGlobalState.forEach { (k, v) -> - GlobalState.globalAttributes[k] = v - } - val expectedAttributes = mockContext.toHashMap() + fakeGlobalState - - // When - testedLogs.debug(fakeMessage, mockContext, mockPromise) - - // Then - verify(mockLogger).d(fakeMessage, attributes = expectedAttributes) - } - - @Test - fun `M forward info log with global state W info()`() { - // Given - fakeGlobalState.forEach { (k, v) -> - GlobalState.globalAttributes[k] = v - } - val expectedAttributes = mockContext.toHashMap() + fakeGlobalState - - // When - testedLogs.info(fakeMessage, mockContext, mockPromise) - - // Then - verify(mockLogger).i(fakeMessage, attributes = expectedAttributes) - } - - @Test - fun `M forward warning log with global state W warn()`() { - // Given - fakeGlobalState.forEach { (k, v) -> - GlobalState.globalAttributes[k] = v - } - val expectedAttributes = mockContext.toHashMap() + fakeGlobalState - - // When - testedLogs.warn(fakeMessage, mockContext, mockPromise) - - // Then - verify(mockLogger).w(fakeMessage, attributes = expectedAttributes) - } - - @Test - fun `M forward error log with global state W error()`() { - // Given - fakeGlobalState.forEach { (k, v) -> - GlobalState.globalAttributes[k] = v - } - val expectedAttributes = mockContext.toHashMap() + fakeGlobalState - - // When - testedLogs.error(fakeMessage, mockContext, mockPromise) - - // Then - verify(mockLogger).e(fakeMessage, attributes = expectedAttributes) - } - - @Test - fun `M forward debug log with error W debugWithError()`() { - // When - testedLogs.debugWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - - // Then - verify(mockLogger).log( - Log.DEBUG, - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - attributes = mockContext.toHashMap() - ) - } - - @Test - fun `M forward info log with error W infoWithError()`() { - // When - testedLogs.infoWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - - // Then - verify(mockLogger).log( - Log.INFO, - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - attributes = mockContext.toHashMap() - ) - } - - @Test - fun `M forward warn log with error W warnWithError()`() { - // When - testedLogs.warnWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - - // Then - verify(mockLogger).log( - Log.WARN, - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - attributes = mockContext.toHashMap() - ) - } - - @Test - fun `M forward error log with error W errorWithError()`() { - // When - testedLogs.errorWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - - // Then - verify(mockLogger).log( - Log.ERROR, - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - attributes = mockContext.toHashMap() - ) - } - - @Test - fun `M not forward logs W SDK is not initialized`() { - // When - whenever(mockDatadog.isInitialized()) doReturn false - var newTestedLogs = DdLogsImplementation(mockLogger, mockDatadog) - newTestedLogs.debug(fakeMessage, mockContext, mockPromise) - newTestedLogs.info(fakeMessage, mockContext, mockPromise) - newTestedLogs.warn(fakeMessage, mockContext, mockPromise) - newTestedLogs.error(fakeMessage, mockContext, mockPromise) - testedLogs.debugWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - testedLogs.infoWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - testedLogs.warnWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - testedLogs.errorWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - - // Then - verifyNoInteractions(mockLogger) - val exceptionCaptor = argumentCaptor() - verify(mockPromise, times(8)).reject(exceptionCaptor.capture()) - assertThat(exceptionCaptor.firstValue.message) - .isEqualTo("DD_INTERNAL_LOG_SENT_BEFORE_SDK_INIT") - - // When SDK is finally initialized - whenever(mockDatadog.isInitialized()) doReturn true - newTestedLogs.debug(fakeMessage, mockContext, mockPromise) - newTestedLogs.info(fakeMessage, mockContext, mockPromise) - newTestedLogs.warn(fakeMessage, mockContext, mockPromise) - newTestedLogs.error(fakeMessage, mockContext, mockPromise) - testedLogs.debugWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - testedLogs.infoWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - testedLogs.warnWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - testedLogs.errorWithError( - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - mockContext, - mockPromise - ) - - // Then - verify(mockLogger).i(fakeMessage, attributes = mockContext.toHashMap()) - verify(mockLogger).d(fakeMessage, attributes = mockContext.toHashMap()) - verify(mockLogger).w(fakeMessage, attributes = mockContext.toHashMap()) - verify(mockLogger).e(fakeMessage, attributes = mockContext.toHashMap()) - verify(mockLogger).log( - Log.DEBUG, - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - attributes = mockContext.toHashMap() - ) - verify(mockLogger).log( - Log.INFO, - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - attributes = mockContext.toHashMap() - ) - verify(mockLogger).log( - Log.WARN, - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - attributes = mockContext.toHashMap() - ) - verify(mockLogger).log( - Log.ERROR, - fakeMessage, - fakeErrorKind, - fakeErrorMessage, - fakeStacktrace, - attributes = mockContext.toHashMap() - ) - } -} diff --git a/packages/core/ios/Sources/AnyEncodable.swift b/packages/core/ios/Sources/AnyEncodable.swift index 39821af87..54ad37bd2 100644 --- a/packages/core/ios/Sources/AnyEncodable.swift +++ b/packages/core/ios/Sources/AnyEncodable.swift @@ -6,11 +6,11 @@ import Foundation -internal func castAttributesToSwift(_ attributes: NSDictionary) -> [String: Encodable] { +public func castAttributesToSwift(_ attributes: NSDictionary) -> [String: Encodable] { return castAttributesToSwift(attributes as? [String: Any] ?? [:]) } -internal func castAttributesToSwift(_ attributes: [String: Any]) -> [String: Encodable] { +public func castAttributesToSwift(_ attributes: [String: Any]) -> [String: Encodable] { var casted: [String: Encodable] = [:] attributes.forEach { key, value in diff --git a/packages/core/ios/Sources/Attributes.swift b/packages/core/ios/Sources/Attributes.swift index adf9638f5..8df2b557d 100644 --- a/packages/core/ios/Sources/Attributes.swift +++ b/packages/core/ios/Sources/Attributes.swift @@ -111,8 +111,8 @@ internal struct InternalConfigurationAttributes { } /// Error messages that can be thrown to the JS SDK -internal struct Errors { +public struct Errors { /// Error thrown when a log was sent before the SDK was initialized. /// Not sending the log prevent the logger to be set to a Noop logger. - static let logSentBeforeSDKInit = "DD_INTERNAL_LOG_SENT_BEFORE_SDK_INIT" + public static let logSentBeforeSDKInit = "DD_INTERNAL_LOG_SENT_BEFORE_SDK_INIT" } diff --git a/packages/core/ios/Sources/DatadogSDKWrapper.swift b/packages/core/ios/Sources/DatadogSDKWrapper.swift index 842ee5d89..7d57b3e80 100644 --- a/packages/core/ios/Sources/DatadogSDKWrapper.swift +++ b/packages/core/ios/Sources/DatadogSDKWrapper.swift @@ -23,7 +23,7 @@ public class DatadogSDKWrapper { // Initialization callbacks internal var onCoreInitializedListeners: [OnCoreInitializedListener] = [] - internal var loggerConfiguration = DatadogLogs.Logger.Configuration() + // Core instance private var coreInstance: DatadogCoreProtocol? = nil @@ -46,7 +46,7 @@ public class DatadogSDKWrapper { // SDK Wrapper internal func initialize( coreConfiguration: Datadog.Configuration, - loggerConfiguration: DatadogLogs.Logger.Configuration, +// loggerConfiguration: DatadogLogs.Logger.Configuration, trackingConsent: TrackingConsent ) -> Void { let core = Datadog.initialize(with: coreConfiguration, trackingConsent: trackingConsent) @@ -55,10 +55,10 @@ public class DatadogSDKWrapper { listener(core) } - self.loggerConfiguration = loggerConfiguration +// self.loggerConfiguration = loggerConfiguration } - internal func isInitialized() -> Bool { + public func isInitialized() -> Bool { return Datadog.isInitialized() } @@ -79,13 +79,13 @@ public class DatadogSDKWrapper { } } - internal func enableLogs(with configuration: Logs.Configuration) { - if let core = coreInstance { - Logs.enable(with: configuration, in: core) - } else { - consolePrint("Core instance was not found when initializing Logs.", .critical) - } - } +// public func enableLogs(with configuration: Logs.Configuration) { +// if let core = coreInstance { +// Logs.enable(with: configuration, in: core) +// } else { +// consolePrint("Core instance was not found when initializing Logs.", .critical) +// } +// } internal func enableTrace(with configuration: Trace.Configuration) { if let core = coreInstance { @@ -102,15 +102,6 @@ public class DatadogSDKWrapper { consolePrint("Core instance was not found when initializing CrashReporting.", .critical) } } - - internal func createLogger() -> LoggerProtocol { - let core = coreInstance ?? { - consolePrint("Core instance was not found when creating Logger.", .critical) - return CoreRegistry.default - }() - - return DatadogLogs.Logger.create(with: loggerConfiguration, in: core) - } // Telemetry internal func sendTelemetryLog(message: String, attributes: [String: any Encodable], config: [String: any Encodable]) { diff --git a/packages/core/ios/Sources/DdSdkNativeInitialization.swift b/packages/core/ios/Sources/DdSdkNativeInitialization.swift index d68d89d06..814dcb9da 100644 --- a/packages/core/ios/Sources/DdSdkNativeInitialization.swift +++ b/packages/core/ios/Sources/DdSdkNativeInitialization.swift @@ -7,7 +7,8 @@ import Foundation import DatadogCore import DatadogRUM -import DatadogLogs +// REMOVED FOR TEST +//import DatadogLogs import DatadogTrace import DatadogCrashReporting import DatadogWebViewTracking @@ -49,7 +50,7 @@ public class DdSdkNativeInitialization: NSObject { let coreConfiguration = self.buildSDKConfiguration(configuration: sdkConfiguration) DatadogSDKWrapper.shared.initialize( coreConfiguration: coreConfiguration, - loggerConfiguration: DatadogLogs.Logger.Configuration(sdkConfiguration), +// loggerConfiguration: DatadogLogs.Logger.Configuration(sdkConfiguration), trackingConsent: sdkConfiguration.trackingConsent ) @@ -80,8 +81,9 @@ public class DdSdkNativeInitialization: NSObject { let rumConfig = buildRUMConfiguration(configuration: sdkConfiguration) DatadogSDKWrapper.shared.enableRUM(with: rumConfig) - let logsConfig = buildLogsConfiguration(configuration: sdkConfiguration) - DatadogSDKWrapper.shared.enableLogs(with: logsConfig) +// REMOVED FOR TEST +// let logsConfig = buildLogsConfiguration(configuration: sdkConfiguration) +// DatadogSDKWrapper.shared.enableLogs(with: logsConfig) let traceConfig = buildTraceConfiguration(configuration: sdkConfiguration) DatadogSDKWrapper.shared.enableTrace(with: traceConfig) @@ -192,17 +194,17 @@ public class DdSdkNativeInitialization: NSObject { telemetrySampleRate: (configuration.telemetrySampleRate as? NSNumber)?.floatValue ?? Float(DefaultConfiguration.telemetrySampleRate) ) } - - func buildLogsConfiguration(configuration: DdSdkConfiguration) -> Logs.Configuration { - var customLogsEndpointURL: URL? = nil - if let customLogsEndpoint = configuration.customEndpoints?.logs as? NSString { - if (customLogsEndpoint != "") { - customLogsEndpointURL = URL(string: "\(customLogsEndpoint)/api/v2/logs" as String) - } - } - - return Logs.Configuration(customEndpoint: customLogsEndpointURL) - } +// REMOVED FOR TEST +// func buildLogsConfiguration(configuration: DdSdkConfiguration) -> Logs.Configuration { +// var customLogsEndpointURL: URL? = nil +// if let customLogsEndpoint = configuration.customEndpoints?.logs as? NSString { +// if (customLogsEndpoint != "") { +// customLogsEndpointURL = URL(string: "\(customLogsEndpoint)/api/v2/logs" as String) +// } +// } +// +// return Logs.Configuration(customEndpoint: customLogsEndpointURL) +// } func buildTraceConfiguration(configuration: DdSdkConfiguration) -> Trace.Configuration { diff --git a/packages/core/ios/Sources/GlobalState.swift b/packages/core/ios/Sources/GlobalState.swift index b932803a1..4c9bf129b 100644 --- a/packages/core/ios/Sources/GlobalState.swift +++ b/packages/core/ios/Sources/GlobalState.swift @@ -19,7 +19,7 @@ internal struct GlobalState { } } -internal extension Dictionary where Key == String, Value == Encodable { +public extension Dictionary where Key == String, Value == Encodable { func mergeWithGlobalAttributes() -> [String: Encodable] { // values of current attributes are more important than values of global attributes, // because they are coming with a current call diff --git a/packages/core/ios/Sources/RNDdSdkConfiguration.swift b/packages/core/ios/Sources/RNDdSdkConfiguration.swift index a765e9759..b6aa8e229 100644 --- a/packages/core/ios/Sources/RNDdSdkConfiguration.swift +++ b/packages/core/ios/Sources/RNDdSdkConfiguration.swift @@ -11,7 +11,7 @@ import Foundation extension NSDictionary { - func asDdSdkConfiguration() -> DdSdkConfiguration { + public func asDdSdkConfiguration() -> DdSdkConfiguration { let clientToken = object(forKey: "clientToken") as? String let env = object(forKey: "env") as? String let applicationId = object(forKey: "applicationId") as? String diff --git a/packages/core/ios/Sources/RNQueueHolderProxy.h b/packages/core/ios/Sources/RNQueueHolderProxy.h new file mode 100644 index 000000000..2d2fc552c --- /dev/null +++ b/packages/core/ios/Sources/RNQueueHolderProxy.h @@ -0,0 +1,11 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RNQueueHolderProxy : NSObject + ++ (dispatch_queue_t)getSharedQueue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/core/ios/Sources/RNQueueHolderProxy.mm b/packages/core/ios/Sources/RNQueueHolderProxy.mm new file mode 100644 index 000000000..96bfe40a5 --- /dev/null +++ b/packages/core/ios/Sources/RNQueueHolderProxy.mm @@ -0,0 +1,10 @@ +#import "RNQueueHolderProxy.h" +#import "DatadogSDKReactNative-Swift.h" + +@implementation RNQueueHolderProxy + ++ (dispatch_queue_t)getSharedQueue { + return [RNQueue getSharedQueue]; +} + +@end diff --git a/packages/core/src/DdSdkReactNative.tsx b/packages/core/src/DdSdkReactNative.tsx index 6969d2c5c..0cd1f5670 100644 --- a/packages/core/src/DdSdkReactNative.tsx +++ b/packages/core/src/DdSdkReactNative.tsx @@ -24,7 +24,6 @@ import type { import { InternalLog } from './InternalLog'; import { SdkVerbosity } from './SdkVerbosity'; import type { TrackingConsent } from './TrackingConsent'; -import { DdLogs } from './logs/DdLogs'; import { DdRum } from './rum/DdRum'; import { DdRumErrorTracking } from './rum/instrumentation/DdRumErrorTracking'; import { DdRumUserInteractionTracking } from './rum/instrumentation/interactionTracking/DdRumUserInteractionTracking'; @@ -388,10 +387,10 @@ export class DdSdkReactNative { if (configuration.trackErrors) { DdRumErrorTracking.startTracking(); } - - if (configuration.logEventMapper) { - DdLogs.registerLogEventMapper(configuration.logEventMapper); - } + // REMOVED FOR TEST + // if (configuration.logEventMapper) { + // DdLogs.registerLogEventMapper(configuration.logEventMapper); + // } if (configuration.errorEventMapper) { DdRum.registerErrorEventMapper(configuration.errorEventMapper); diff --git a/packages/core/src/DdSdkReactNativeConfiguration.tsx b/packages/core/src/DdSdkReactNativeConfiguration.tsx index 158d258eb..9246b4526 100644 --- a/packages/core/src/DdSdkReactNativeConfiguration.tsx +++ b/packages/core/src/DdSdkReactNativeConfiguration.tsx @@ -7,7 +7,6 @@ import type { ProxyConfiguration } from './ProxyConfiguration'; import type { SdkVerbosity } from './SdkVerbosity'; import { TrackingConsent } from './TrackingConsent'; -import type { LogEventMapper } from './logs/types'; import type { ActionEventMapper } from './rum/eventMappers/actionEventMapper'; import type { ErrorEventMapper } from './rum/eventMappers/errorEventMapper'; import type { ResourceEventMapper } from './rum/eventMappers/resourceEventMapper'; @@ -341,7 +340,9 @@ export class DdSdkReactNativeConfiguration { */ public actionNameAttribute?: string; - public logEventMapper: LogEventMapper | null = DEFAULTS.logEventMapper; + // THIS TYPE NEEDS TO COME FROM CORE + // public logEventMapper: LogEventMapper | null = DEFAULTS.logEventMapper; + public logEventMapper: any | null = DEFAULTS.logEventMapper; public errorEventMapper: ErrorEventMapper | null = DEFAULTS.errorEventMapper; @@ -380,7 +381,9 @@ export type AutoInstrumentationConfiguration = { readonly firstPartyHosts?: FirstPartyHostsConfiguration; readonly resourceTracingSamplingRate?: number; readonly trackErrors: boolean; - readonly logEventMapper?: LogEventMapper | null; + // THIS TYPE NEEDS TO COME FROM CORE + // readonly logEventMapper?: LogEventMapper | null; + readonly logEventMapper?: any | null; readonly errorEventMapper?: ErrorEventMapper | null; readonly resourceEventMapper?: ResourceEventMapper | null; readonly actionEventMapper?: ActionEventMapper | null; @@ -397,7 +400,9 @@ export type AutoInstrumentationParameters = { readonly firstPartyHosts: FirstPartyHostsConfiguration; readonly resourceTracingSamplingRate: number; readonly trackErrors: boolean; - readonly logEventMapper: LogEventMapper | null; + // THIS TYPE NEEDS TO COME FROM CORE + // readonly logEventMapper: LogEventMapper | null; + readonly logEventMapper: any | null; readonly errorEventMapper: ErrorEventMapper | null; readonly resourceEventMapper: ResourceEventMapper | null; readonly actionEventMapper: ActionEventMapper | null; diff --git a/packages/core/src/index.tsx b/packages/core/src/index.tsx index df6ef045e..512a100ff 100644 --- a/packages/core/src/index.tsx +++ b/packages/core/src/index.tsx @@ -17,11 +17,12 @@ import type { PartialInitializationConfiguration } from './DdSdkReactNativeConfiguration'; import { DdSdkReactNative } from './DdSdkReactNative'; -import { InternalLog } from './InternalLog'; +import { InternalLog, DATADOG_MESSAGE_PREFIX } from './InternalLog'; import { ProxyConfiguration, ProxyType } from './ProxyConfiguration'; import { SdkVerbosity } from './SdkVerbosity'; import { TrackingConsent } from './TrackingConsent'; -import { DdLogs } from './logs/DdLogs'; +import { DdAttributes } from './rum/DdAttributes'; +// import { DdLogs } from './logs/DdLogs'; import { DdRum } from './rum/DdRum'; import { DatadogTracingContext } from './rum/instrumentation/resourceTracking/distributedTracing/DatadogTracingContext'; import { DatadogTracingIdentifier } from './rum/instrumentation/resourceTracking/distributedTracing/DatadogTracingIdentifier'; @@ -36,20 +37,26 @@ import { } from './rum/instrumentation/resourceTracking/graphql/graphqlHeaders'; import { RumActionType, ErrorSource, PropagatorType } from './rum/types'; import type { FirstPartyHost } from './rum/types'; +import type { Attributes } from './sdk/AttributesSingleton/types'; import { DatadogProvider } from './sdk/DatadogProvider/DatadogProvider'; import { DdSdk } from './sdk/DdSdk'; +import { EventMapper } from './sdk/EventMappers/EventMapper'; +import type { AdditionalEventDataForMapper } from './sdk/EventMappers/EventMapper'; import { FileBasedConfiguration } from './sdk/FileBasedConfiguration/FileBasedConfiguration'; import { DdTrace } from './trace/DdTrace'; +import type { UserInfo } from './types'; +import { validateContext } from './utils/argsUtils'; import { DefaultTimeProvider } from './utils/time-provider/DefaultTimeProvider'; import { TimeProvider } from './utils/time-provider/TimeProvider'; import type { Timestamp } from './utils/time-provider/TimeProvider'; export { + EventMapper, DatadogProvider, DatadogProviderConfiguration, FileBasedConfiguration, InitializationMode, - DdLogs, + // DdLogs, DdTrace, DdRum, RumActionType, @@ -75,10 +82,16 @@ export { TracingIdType, TracingIdFormat, DatadogTracingIdentifier, - DatadogTracingContext + DatadogTracingContext, + DdAttributes, + validateContext, + DATADOG_MESSAGE_PREFIX }; export type { + AdditionalEventDataForMapper, + Attributes, + UserInfo, Timestamp, FirstPartyHost, AutoInstrumentationConfiguration, diff --git a/packages/core/src/logs/__tests__/DdLogs.test.ts b/packages/core/src/logs/__tests__/DdLogs.test.ts deleted file mode 100644 index f99280bfe..000000000 --- a/packages/core/src/logs/__tests__/DdLogs.test.ts +++ /dev/null @@ -1,1032 +0,0 @@ -/* - * 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 2016-Present Datadog, Inc. - */ - -import { NativeModules } from 'react-native'; - -import { DdSdkReactNativeConfiguration } from '../../DdSdkReactNativeConfiguration'; -import { DdSdkReactNative } from '../../DdSdkReactNative'; -import { InternalLog } from '../../InternalLog'; -import { SdkVerbosity } from '../../SdkVerbosity'; -import type { DdNativeLogsType } from '../../nativeModulesTypes'; -import { ErrorSource } from '../../rum/types'; -import { DdLogs } from '../DdLogs'; -import type { LogEventMapper } from '../types'; - -jest.mock('../../InternalLog', () => { - return { - InternalLog: { - log: jest.fn() - }, - DATADOG_MESSAGE_PREFIX: 'DATADOG:' - }; -}); - -describe('DdLogs', () => { - describe('log event mapper', () => { - beforeEach(() => { - jest.clearAllMocks(); - DdLogs.unregisterLogEventMapper(); - }); - - it('registers event mapper and maps logs', async () => { - const logEventMapper: LogEventMapper = log => { - return { - message: 'new message', - context: { newContext: 'context' }, - status: 'info', - userInfo: {} - }; - }; - DdLogs.registerLogEventMapper(logEventMapper); - - await DdLogs.info('original message', {}); - expect( - NativeModules.DdLogs.info - ).toHaveBeenCalledWith('new message', { newContext: 'context' }); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - 'Tracking info log "new message"', - 'debug' - ); - - await DdLogs.debug( - 'original message', - 'TypeError', - 'error message', - 'stack', - {} - ); - expect(NativeModules.DdLogs.debugWithError).toHaveBeenCalledWith( - 'new message', - undefined, - undefined, - undefined, - { - newContext: 'context', - '_dd.error.source_type': 'react-native' - } - ); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 2, - 'Tracking debug log "new message"', - 'debug' - ); - }); - - it('registers event mapper and maps logs with errors', async () => { - const logEventMapper: LogEventMapper = log => { - log.message = 'new message'; - if (log.errorKind) { - log.errorKind = 'NewErrorType'; - } - if (log.errorMessage) { - log.errorMessage = 'new error message'; - } - if (log.stacktrace) { - log.stacktrace = 'new stacktrace'; - } - log.context = { newContext: 'context' }; - return log; - }; - DdLogs.registerLogEventMapper(logEventMapper); - - await DdLogs.info('original message', {}); - expect( - NativeModules.DdLogs.info - ).toHaveBeenCalledWith('new message', { newContext: 'context' }); - await DdLogs.info( - 'original message', - 'TypeError', - 'error message', - 'stack', - {} - ); - expect(NativeModules.DdLogs.infoWithError).toHaveBeenCalledWith( - 'new message', - 'NewErrorType', - 'new error message', - 'new stacktrace', - { - newContext: 'context', - '_dd.error.source_type': 'react-native' - } - ); - }); - - it('sends initial log if no event mapper is registered', async () => { - await DdLogs.info('original message', {}); - expect(NativeModules.DdLogs.info).toHaveBeenCalledWith( - 'original message', - {} - ); - }); - - it('drops the event if the mapper returns null', async () => { - const logEventMapper: LogEventMapper = log => { - return null; - }; - DdLogs.registerLogEventMapper(logEventMapper); - - await DdLogs.info('original message', {}); - expect(NativeModules.DdLogs.info).not.toHaveBeenCalled(); - expect(InternalLog.log).toHaveBeenCalledWith( - 'info log dropped by log mapper: "original message"', - 'debug' - ); - }); - - it('log with error events can be filtered by error source', async () => { - const logEventMapper: LogEventMapper = logEvent => { - if (logEvent.source === ErrorSource.CONSOLE) { - return null; - } - - return logEvent; - }; - - DdLogs.registerLogEventMapper(logEventMapper); - - await DdLogs.error( - 'message', - 'kind', - 'message', - 'stacktrace', - {}, - 'fingerprint', - ErrorSource.CONSOLE - ); - - // Call with filtered ErrorSource.CONSOLE type - expect(NativeModules.DdLogs.error).not.toHaveBeenCalled(); - expect(InternalLog.log).toHaveBeenCalledWith( - 'error log dropped by log mapper: "message"', - 'debug' - ); - - // Call with valid ErrorSource.CUSTOM type - await DdLogs.error( - 'message', - 'kind', - 'message', - 'stacktrace', - {}, - 'fingerprint', - ErrorSource.CUSTOM - ); - - expect(NativeModules.DdLogs.errorWithError).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { - '_dd.error.fingerprint': 'fingerprint', - '_dd.error.source_type': 'react-native' - } - ); - expect(InternalLog.log).toHaveBeenCalledWith( - 'Tracking error log "message"', - 'debug' - ); - }); - - it('console errors can be filtered with mappers when trackErrors=true', async () => { - // GIVEN - const fakeAppId = '1'; - const fakeClientToken = '2'; - const fakeEnvName = 'env'; - const configuration = new DdSdkReactNativeConfiguration( - fakeClientToken, - fakeEnvName, - fakeAppId, - false, - false, - true // Track Errors - ); - - // Register log event mapper to filter console log events - configuration.logEventMapper = logEvent => { - if (logEvent.source === ErrorSource.CONSOLE) { - return null; - } - - return logEvent; - }; - - NativeModules.DdSdk.initialize.mockResolvedValue(null); - - // WHEN - await DdSdkReactNative.initialize(configuration); - - console.error('console-error-message'); - expect(NativeModules.DdLogs.error).not.toHaveBeenCalled(); - expect(InternalLog.log).toHaveBeenCalledWith( - 'error log dropped by log mapper: "console-error-message"', - 'debug' - ); - - // Call with valid ErrorSource.CUSTOM type - await DdLogs.error( - 'message', - 'kind', - 'message', - 'stacktrace', - {}, - 'fingerprint', - ErrorSource.CUSTOM - ); - - expect(NativeModules.DdLogs.errorWithError).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { - '_dd.error.fingerprint': 'fingerprint', - '_dd.error.source_type': 'react-native' - } - ); - expect(InternalLog.log).toHaveBeenCalledWith( - 'Tracking error log "message"', - 'debug' - ); - }); - - it('console errors are reported in logs when trackErrors=true', async () => { - // GIVEN - const fakeAppId = '1'; - const fakeClientToken = '2'; - const fakeEnvName = 'env'; - const configuration = new DdSdkReactNativeConfiguration( - fakeClientToken, - fakeEnvName, - fakeAppId, - false, - false, - true // Track Errors - ); - - NativeModules.DdSdk.initialize.mockResolvedValue(null); - - // WHEN - await DdSdkReactNative.initialize(configuration); - - console.error('console-error-message'); - expect(NativeModules.DdLogs.error).not.toHaveBeenCalled(); - expect(InternalLog.log).toHaveBeenCalledWith( - 'Tracking error log "console-error-message"', - 'debug' - ); - }); - }); - - describe('log with error', () => { - beforeEach(() => { - jest.clearAllMocks(); - DdLogs.unregisterLogEventMapper(); - }); - it.each([ - ['kind', 'message', 'stacktrace', { context: 'value' }], - // 1 argument is undefined - [undefined, 'message', 'stacktrace', { context: 'value' }], - ['kind', undefined, 'stacktrace', { context: 'value' }], - ['kind', 'message', undefined, { context: 'value' }], - ['kind', 'message', 'stacktrace', undefined], - // 2 arguments are undefined - [undefined, undefined, 'stacktrace', { context: 'value' }], - [undefined, 'message', undefined, { context: 'value' }], - [undefined, 'message', 'stacktrace', undefined], - ['kind', undefined, undefined, { context: 'value' }], - ['kind', undefined, 'stacktrace', undefined], - ['kind', 'message', undefined, undefined], - // 3 arguments are undefined - [undefined, undefined, 'stacktrace', undefined], - [undefined, 'message', undefined, undefined], - ['kind', undefined, undefined, undefined], - [undefined, undefined, undefined, { context: 'value' }] - ])( - 'sends error info when provided for %s %s %s %s', - async (errorKind, errorMessage, stacktrace, context) => { - await DdLogs.info( - 'message', - errorKind, - errorMessage, - stacktrace, - context - ); - expect(NativeModules.DdLogs.infoWithError).toHaveBeenCalledWith( - 'message', - errorKind, - errorMessage, - stacktrace, - { - ...(context || {}), - '_dd.error.source_type': 'react-native' - } - ); - } - ); - - it.each([ - [ - 'kind', - 'message', - 'stacktrace', - { context: 'value' }, - 'custom-fingerprint-0' - ], - // 1 argument is undefined - [ - undefined, - 'message', - 'stacktrace', - { context: 'value' }, - 'custom-fingerprint-1' - ], - [ - 'kind', - undefined, - 'stacktrace', - { context: 'value' }, - 'custom-fingerprint-2' - ], - [ - 'kind', - 'message', - undefined, - { context: 'value' }, - 'custom-fingerprint-3' - ], - ['kind', 'message', 'stacktrace', undefined, 'custom-fingerprint'], - // 2 arguments are undefined - [ - undefined, - undefined, - 'stacktrace', - { context: 'value' }, - 'custom-fingerprint-4' - ], - [ - undefined, - 'message', - undefined, - { context: 'value' }, - 'custom-fingerprint-5' - ], - [ - undefined, - 'message', - 'stacktrace', - undefined, - 'custom-fingerprint-6' - ], - [ - 'kind', - undefined, - undefined, - { context: 'value' }, - 'custom-fingerprint-7' - ], - [ - 'kind', - undefined, - 'stacktrace', - undefined, - 'custom-fingerprint-8' - ], - ['kind', 'message', undefined, undefined, 'custom-fingerprint-9'], - // 3 arguments are undefined - [ - undefined, - undefined, - 'stacktrace', - undefined, - 'custom-fingerprint-10' - ], - [ - undefined, - 'message', - undefined, - undefined, - 'custom-fingerprint-11' - ], - ['kind', undefined, undefined, undefined, 'custom-fingerprint-12'], - [ - undefined, - undefined, - undefined, - { context: 'value' }, - 'custom-fingerprint-13' - ] - ])( - 'sends error info with custom fingerprint when provided for %s %s %s %s %s', - async ( - errorKind, - errorMessage, - stacktrace, - context, - fingerprint - ) => { - await DdLogs.info( - 'message', - errorKind, - errorMessage, - stacktrace, - context, - fingerprint - ); - expect(NativeModules.DdLogs.infoWithError).toHaveBeenCalledWith( - 'message', - errorKind, - errorMessage, - stacktrace, - { - ...(context || {}), - '_dd.error.source_type': 'react-native', - '_dd.error.fingerprint': fingerprint - } - ); - } - ); - - it('does not send error info when no error and no context is passed', async () => { - await DdLogs.info( - 'message', - undefined, - undefined, - undefined, - undefined - ); - expect(NativeModules.DdLogs.info).toHaveBeenCalledWith( - 'message', - {} - ); - }); - }); - - describe('when SDK is not initialized', () => { - beforeEach(() => { - jest.clearAllMocks(); - DdLogs.unregisterLogEventMapper(); - }); - - it('does not crash and warns user', async () => { - (NativeModules.DdLogs.info as jest.MockedFunction< - DdNativeLogsType['debug'] - >).mockRejectedValueOnce( - new Error('DD_INTERNAL_LOG_SENT_BEFORE_SDK_INIT') - ); - const consoleSpy = jest.spyOn(console, 'warn'); - await DdLogs.info('original message', {}); - expect(consoleSpy).toHaveBeenCalledWith( - 'DATADOG: Dropping info log as the SDK is not initialized yet: "original message"' - ); - }); - }); - - describe('log context', () => { - beforeEach(() => { - jest.clearAllMocks(); - DdLogs.unregisterLogEventMapper(); - }); - - describe('debug logs', () => { - it('native context is empty W context is undefined', async () => { - await DdLogs.debug('message', undefined); - expect(NativeModules.DdLogs.debug).toHaveBeenCalledWith( - 'message', - {} - ); - }); - - it('native context is an object with nested property W context is an array', async () => { - await DdLogs.debug('message', [1, 2, 3]); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.WARN - ); - expect( - NativeModules.DdLogs.debug - ).toHaveBeenCalledWith('message', { context: [1, 2, 3] }); - }); - - it('native context is empty W context is raw type', async () => { - const obj: any = 123; - await DdLogs.debug('message', obj); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.ERROR - ); - expect(NativeModules.DdLogs.debug).toHaveBeenCalledWith( - 'message', - {} - ); - }); - - it('native context is unmodified W context is a valid object', async () => { - await DdLogs.debug('message', { test: '123' }); - expect( - NativeModules.DdLogs.debug - ).toHaveBeenCalledWith('message', { test: '123' }); - }); - }); - - describe('warn logs', () => { - it('native context is empty W context is undefined', async () => { - await DdLogs.warn('message', undefined); - expect(NativeModules.DdLogs.warn).toHaveBeenCalledWith( - 'message', - {} - ); - }); - - it('native context is an object with nested property W context is an array', async () => { - await DdLogs.warn('message', [1, 2, 3]); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.WARN - ); - expect( - NativeModules.DdLogs.warn - ).toHaveBeenCalledWith('message', { context: [1, 2, 3] }); - }); - - it('native context is empty W context is raw type', async () => { - const obj: any = 123; - await DdLogs.warn('message', obj); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.ERROR - ); - expect(NativeModules.DdLogs.warn).toHaveBeenCalledWith( - 'message', - {} - ); - }); - - it('native context is unmodified W context is a valid object', async () => { - await DdLogs.warn('message', { test: '123' }); - expect( - NativeModules.DdLogs.warn - ).toHaveBeenCalledWith('message', { test: '123' }); - }); - }); - - describe('info logs', () => { - it('native context is empty W context is undefined', async () => { - await DdLogs.info('message', undefined); - expect(NativeModules.DdLogs.info).toHaveBeenCalledWith( - 'message', - {} - ); - }); - - it('native context is an object with nested property W context is an array', async () => { - await DdLogs.info('message', [1, 2, 3]); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.WARN - ); - expect( - NativeModules.DdLogs.info - ).toHaveBeenCalledWith('message', { context: [1, 2, 3] }); - }); - - it('native context is empty W context is raw type', async () => { - const obj: any = 123; - await DdLogs.info('message', obj); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.ERROR - ); - expect(NativeModules.DdLogs.info).toHaveBeenCalledWith( - 'message', - {} - ); - }); - - it('native context is unmodified W context is a valid object', async () => { - await DdLogs.info('message', { test: '123' }); - expect( - NativeModules.DdLogs.info - ).toHaveBeenCalledWith('message', { test: '123' }); - }); - }); - - describe('error logs', () => { - it('native context is empty W context is undefined', async () => { - await DdLogs.error('message', undefined); - expect(NativeModules.DdLogs.error).toHaveBeenCalledWith( - 'message', - {} - ); - }); - - it('native context is an object with nested property W context is an array', async () => { - await DdLogs.error('message', [1, 2, 3]); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.WARN - ); - expect( - NativeModules.DdLogs.error - ).toHaveBeenCalledWith('message', { context: [1, 2, 3] }); - }); - - it('native context is empty W context is raw type', async () => { - const obj: any = 123; - await DdLogs.error('message', obj); - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.ERROR - ); - expect(NativeModules.DdLogs.error).toHaveBeenCalledWith( - 'message', - {} - ); - }); - - it('native context is unmodified W context is a valid object', async () => { - await DdLogs.error('message', { test: '123' }); - expect( - NativeModules.DdLogs.error - ).toHaveBeenCalledWith('message', { test: '123' }); - }); - }); - }); - - describe('log with error context', () => { - beforeEach(() => { - jest.clearAllMocks(); - DdLogs.unregisterLogEventMapper(); - }); - - describe('debug logs', () => { - it('native context is empty W context is undefined', async () => { - await DdLogs.debug( - 'message', - 'kind', - 'message', - 'stacktrace', - undefined - ); - expect( - NativeModules.DdLogs.debugWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { '_dd.error.source_type': 'react-native' } - ); - }); - - it('native context is an object with nested property W context is an array', async () => { - await DdLogs.debug('message', 'kind', 'message', 'stacktrace', [ - 1, - 2, - 3 - ]); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.WARN - ); - - expect( - NativeModules.DdLogs.debugWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { - context: [1, 2, 3], - '_dd.error.source_type': 'react-native' - } - ); - }); - - it('native context is empty W context is raw type', async () => { - const obj: any = 123; - await DdLogs.debug( - 'message', - 'kind', - 'message', - 'stacktrace', - obj - ); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.ERROR - ); - - expect( - NativeModules.DdLogs.debugWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { '_dd.error.source_type': 'react-native' } - ); - }); - - it('native context is unmodified W context is a valid object', async () => { - await DdLogs.debug('message', 'kind', 'message', 'stacktrace', { - test: '123' - }); - expect( - NativeModules.DdLogs.debugWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { test: '123', '_dd.error.source_type': 'react-native' } - ); - }); - }); - - describe('warn logs', () => { - it('native context is empty W context is undefined', async () => { - await DdLogs.warn( - 'message', - 'kind', - 'message', - 'stacktrace', - undefined - ); - expect( - NativeModules.DdLogs.warnWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { '_dd.error.source_type': 'react-native' } - ); - }); - - it('native context is an object with nested property W context is an array', async () => { - await DdLogs.warn('message', 'kind', 'message', 'stacktrace', [ - 1, - 2, - 3 - ]); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.WARN - ); - - expect(NativeModules.DdLogs.warnWithError).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { - context: [1, 2, 3], - '_dd.error.source_type': 'react-native' - } - ); - }); - - it('native context is empty W context is raw type', async () => { - const obj: any = 123; - await DdLogs.warn( - 'message', - 'kind', - 'message', - 'stacktrace', - obj - ); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.ERROR - ); - - expect( - NativeModules.DdLogs.warnWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { '_dd.error.source_type': 'react-native' } - ); - }); - - it('native context is unmodified W context is a valid object', async () => { - await DdLogs.warn('message', 'kind', 'message', 'stacktrace', { - test: '123' - }); - expect( - NativeModules.DdLogs.warnWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { test: '123', '_dd.error.source_type': 'react-native' } - ); - }); - }); - - describe('info logs', () => { - it('native context is empty W context is undefined', async () => { - await DdLogs.info( - 'message', - 'kind', - 'message', - 'stacktrace', - undefined - ); - expect( - NativeModules.DdLogs.infoWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { '_dd.error.source_type': 'react-native' } - ); - }); - - it('native context is an object with nested property W context is an array', async () => { - await DdLogs.info('message', 'kind', 'message', 'stacktrace', [ - 1, - 2, - 3 - ]); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.WARN - ); - - expect(NativeModules.DdLogs.infoWithError).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { - context: [1, 2, 3], - '_dd.error.source_type': 'react-native' - } - ); - }); - - it('native context is empty W context is raw type', async () => { - const obj: any = 123; - await DdLogs.info( - 'message', - 'kind', - 'message', - 'stacktrace', - obj - ); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.ERROR - ); - - expect( - NativeModules.DdLogs.infoWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { '_dd.error.source_type': 'react-native' } - ); - }); - - it('native context is unmodified W context is a valid object', async () => { - await DdLogs.info('message', 'kind', 'message', 'stacktrace', { - test: '123' - }); - expect( - NativeModules.DdLogs.infoWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { test: '123', '_dd.error.source_type': 'react-native' } - ); - }); - }); - - describe('error logs', () => { - it('native context is empty W context is undefined', async () => { - await DdLogs.error( - 'message', - 'kind', - 'message', - 'stacktrace', - undefined - ); - expect( - NativeModules.DdLogs.errorWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { '_dd.error.source_type': 'react-native' } - ); - }); - - it('native context is an object with nested property W context is an array', async () => { - await DdLogs.error('message', 'kind', 'message', 'stacktrace', [ - 1, - 2, - 3 - ]); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.WARN - ); - - expect( - NativeModules.DdLogs.errorWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { - context: [1, 2, 3], - '_dd.error.source_type': 'react-native' - } - ); - }); - - it('native context is empty W context is raw type', async () => { - const obj: any = 123; - await DdLogs.error( - 'message', - 'kind', - 'message', - 'stacktrace', - obj - ); - - expect(InternalLog.log).toHaveBeenNthCalledWith( - 1, - expect.anything(), - SdkVerbosity.ERROR - ); - - expect( - NativeModules.DdLogs.errorWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { '_dd.error.source_type': 'react-native' } - ); - }); - - it('native context is unmodified W context is a valid object', async () => { - await DdLogs.error('message', 'kind', 'message', 'stacktrace', { - test: '123' - }); - expect( - NativeModules.DdLogs.errorWithError - ).toHaveBeenCalledWith( - 'message', - 'kind', - 'message', - 'stacktrace', - { test: '123', '_dd.error.source_type': 'react-native' } - ); - }); - }); - }); -}); diff --git a/packages/core/src/logs/__tests__/eventMapper.test.ts b/packages/core/src/logs/__tests__/eventMapper.test.ts deleted file mode 100644 index 0999a6058..000000000 --- a/packages/core/src/logs/__tests__/eventMapper.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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 2016-Present Datadog, Inc. - */ - -/* eslint-disable @typescript-eslint/ban-ts-comment */ -import { ErrorSource } from '../../rum/types'; -import { formatRawLogToLogEvent } from '../eventMapper'; - -describe('formatRawLogToLogEvent', () => { - it('formats a raw log without context and userInfo to a LogEvent', () => { - expect( - formatRawLogToLogEvent( - { message: 'original', context: {}, status: 'info' }, - { userInfo: {}, attributes: {} } - ) - ).toEqual({ - message: 'original', - context: {}, - status: 'info', - userInfo: {}, - attributes: {} - }); - }); - - it('formats a raw log with context, userInfo and attributes to a LogEvent', () => { - expect( - formatRawLogToLogEvent( - { - message: 'original', - context: { loggedIn: true }, - status: 'info' - }, - { - userInfo: { - name: 'userName', - extraInfo: { loggedIn: true } - }, - attributes: { appType: 'student' } - } - ) - ).toEqual({ - message: 'original', - context: { loggedIn: true }, - status: 'info', - userInfo: { - name: 'userName', - extraInfo: { loggedIn: true } - }, - attributes: { appType: 'student' } - }); - }); - - it('formats a raw log with error attributes and with context, userInfo and attributes to a LogEvent', () => { - expect( - formatRawLogToLogEvent( - { - message: 'original', - errorKind: 'TypeError', - errorMessage: 'something went wrong', - stacktrace: 'stacktrace', - context: { loggedIn: true }, - status: 'info' - }, - { - userInfo: { - name: 'userName', - extraInfo: { loggedIn: true } - }, - attributes: { appType: 'student' } - } - ) - ).toEqual({ - message: 'original', - errorKind: 'TypeError', - errorMessage: 'something went wrong', - stacktrace: 'stacktrace', - context: { loggedIn: true }, - status: 'info', - userInfo: { - name: 'userName', - extraInfo: { loggedIn: true } - }, - attributes: { appType: 'student' } - }); - }); - - it('formats a raw log with error attributes and with context, userInfo, attributes and source to a LogEvent', () => { - expect( - formatRawLogToLogEvent( - { - message: 'original', - errorKind: 'TypeError', - errorMessage: 'something went wrong', - stacktrace: 'stacktrace', - context: { loggedIn: true }, - status: 'info', - source: ErrorSource.CONSOLE - }, - { - userInfo: { - name: 'userName', - extraInfo: { loggedIn: true } - }, - attributes: { appType: 'student' } - } - ) - ).toEqual({ - message: 'original', - errorKind: 'TypeError', - errorMessage: 'something went wrong', - stacktrace: 'stacktrace', - context: { loggedIn: true }, - status: 'info', - source: ErrorSource.CONSOLE, - userInfo: { - name: 'userName', - extraInfo: { loggedIn: true } - }, - attributes: { appType: 'student' } - }); - }); -}); diff --git a/packages/core/src/nativeModulesTypes.ts b/packages/core/src/nativeModulesTypes.ts index b05fb6e95..361bf227f 100644 --- a/packages/core/src/nativeModulesTypes.ts +++ b/packages/core/src/nativeModulesTypes.ts @@ -4,7 +4,7 @@ * Copyright 2016-Present Datadog, Inc. */ -import type { Spec as NativeDdLogs } from './specs/NativeDdLogs'; +// import type { Spec as NativeDdLogs } from './specs/NativeDdLogs'; import type { Spec as NativeDdRum } from './specs/NativeDdRum'; import type { Spec as NativeDdSdk } from './specs/NativeDdSdk'; import type { Spec as NativeDdTrace } from './specs/NativeDdTrace'; @@ -17,7 +17,7 @@ import type { Spec as NativeDdTrace } from './specs/NativeDdTrace'; /** * The entry point to use Datadog's Logs feature. */ -export type DdNativeLogsType = NativeDdLogs; +// export type DdNativeLogsType = NativeDdLogs; /** * The entry point to use Datadog's Trace feature. diff --git a/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx b/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx index 04b01290c..2ef77c4e2 100644 --- a/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx +++ b/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx @@ -8,7 +8,6 @@ import type { ErrorHandlerCallback } from 'react-native'; import { InternalLog } from '../../InternalLog'; import { SdkVerbosity } from '../../SdkVerbosity'; -import { DdLogs } from '../../logs/DdLogs'; import { getErrorMessage, getErrorStackTrace, @@ -142,28 +141,36 @@ export class DdRumErrorTracking { message: string, source: ErrorSource, stacktrace: string, - errorName: string, + // removed + _errorName: string, context: object = {} - ): Promise<[void, void]> => { - return Promise.all([ - DdRum.addError( - message, - source, - stacktrace, - getErrorContext(context) - ), - DdLogs.error( - message, - errorName, - message, - stacktrace, - { - ...context, - '_dd.error_log.is_crash': true - }, - undefined, - source - ) - ]); + ): Promise => { + return DdRum.addError( + message, + source, + stacktrace, + getErrorContext(context) + ); + // Direct use of DdLogs from RUM + // return Promise.all([ + // DdRum.addError( + // message, + // source, + // stacktrace, + // getErrorContext(context) + // ), + // DdLogs.error( + // message, + // errorName, + // message, + // stacktrace, + // { + // ...context, + // '_dd.error_log.is_crash': true + // }, + // undefined, + // source + // ) + // ]); }; } diff --git a/packages/logs/DatadogSDKReactNativeLogs.podspec b/packages/logs/DatadogSDKReactNativeLogs.podspec new file mode 100644 index 000000000..843e5685b --- /dev/null +++ b/packages/logs/DatadogSDKReactNativeLogs.podspec @@ -0,0 +1,64 @@ +require "json" + +package = JSON.parse(File.read(File.join(__dir__, "package.json"))) +folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32' + +Pod::Spec.new do |s| + s.name = "DatadogSDKReactNativeLogs" + s.version = package["version"] + s.summary = package["description"] + s.homepage = package["homepage"] + s.license = package["license"] + s.authors = package["author"] + + s.platforms = { :ios => "12.0", :tvos => "12.0" } + s.source = { :git => "https://github.com/DataDog/dd-sdk-reactnative.git", :tag => "#{s.version}" } + + s.source_files = "ios/Sources/*.{h,m,mm,swift}" + + s.dependency "React-Core" + + # /!\ Remember to keep the version in sync with DatadogSDKReactNative.podspec + s.dependency 'DatadogLogs', '2.29.0' + s.dependency 'DatadogCore', '2.29.0' + s.dependency 'DatadogInternal', '2.29.0' + s.dependency 'DatadogSDKReactNative' + + s.test_spec 'Tests' do |test_spec| + test_spec.dependency "React-RCTText" + test_spec.source_files = 'ios/Tests/*.swift' + test_spec.platforms = { :ios => "13.4", :tvos => "13.4" } + end + + + xcconfig = { + "HEADER_SEARCH_PATHS" => "$(inherited) " + + "$(PODS_ROOT)/React-RCTFabric/** " + + "$(PODS_ROOT)/React-FabricComponents/** " + + "${PODS_CONFIGURATION_BUILD_DIR}/React-Fabric/React_RCTFabric.framework/Headers/** " + + "$(PODS_CONFIGURATION_BUILD_DIR)/React-FabricComponents/React_FabricComponents.framework/Headers/**", + "USER_HEADER_SEARCH_PATHS" => "$(inherited) " + + "$(PODS_ROOT)/React-RCTFabric/** " + + "$(PODS_ROOT)/React-FabricComponents/** " + + "${PODS_CONFIGURATION_BUILD_DIR}/React-Fabric/React_RCTFabric.framework/Headers/** " + + "$(PODS_CONFIGURATION_BUILD_DIR)/React-FabricComponents/React_FabricComponents.framework/Headers/**" + } + + if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then + s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1" + + xcconfig.merge!({ + "DEFINES_MODULE" => "YES", + "CLANG_CXX_LANGUAGE_STANDARD" => "c++17" + }) + end + + s.pod_target_xcconfig = xcconfig + + if respond_to?(:install_modules_dependencies, true) + install_modules_dependencies(s) + # else + # s.dependency "React-Core" + end + +end diff --git a/packages/logs/android/build.gradle b/packages/logs/android/build.gradle new file mode 100644 index 000000000..fda51aefd --- /dev/null +++ b/packages/logs/android/build.gradle @@ -0,0 +1,249 @@ +import java.nio.file.Paths +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +buildscript { + // Buildscript is evaluated before everything else so we can't use getExtOrDefault + def kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : project.properties['DatadogSDKReactNativeLogs_kotlinVersion'] + + repositories { + mavenCentral() + google() + gradlePluginPortal() + } + + dependencies { + classpath 'com.android.tools.build:gradle:7.2.2' + // noinspection DifferentKotlinGradleVersion + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "org.jlleitschuh.gradle:ktlint-gradle:11.5.1" + classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.18.0" + classpath 'com.github.bjoernq:unmockplugin:0.7.9' + } +} + + +apply plugin: 'de.mobilej.unmock' + +def isNewArchitectureEnabled() { + return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true" +} + +apply plugin: 'com.android.library' +if (isNewArchitectureEnabled()) { + apply plugin: 'com.facebook.react' +} +apply plugin: 'kotlin-android' +apply plugin: 'org.jlleitschuh.gradle.ktlint' +apply plugin: "io.gitlab.arturbosch.detekt" + +/** + * Finds the path of the installed npm package with the given name using Node's + * module resolution algorithm, which searches "node_modules" directories up to + * the file system root. + * This enables us to handle monorepos without requiring the node executable. + * + * The search begins at the given base directory (a File object). The returned + * path is a string. + */ +static def findNodeModulePath(baseDir, packageName) { + def basePath = baseDir.toPath().normalize() + // Node's module resolution algorithm searches up to the root directory, + // after which the base path will be null + while (basePath) { + def candidatePath = Paths.get(basePath.toString(), "node_modules", packageName) + if (candidatePath.toFile().exists()) { + return candidatePath.toString() + } + basePath = basePath.getParent() + } + return null +} + +def resolveReactNativeDirectory() { + def reactNativeLocation = rootProject.hasProperty("reactNativeDir") ? rootProject.getProperty("reactNativeDir") : null + + if (reactNativeLocation != null) { + return file(reactNativeLocation) + } + + def reactNativePath = findNodeModulePath(projectDir, "react-native") + + if (reactNativePath != null) { + return file(reactNativePath) + } + + throw new Exception( + "${project.name}: Failed to resolve 'react-native' in the project. " + + "Altenatively, you can specify 'reactNativeDir' with the path to 'react-native' in your 'gradle.properties' file." + ) +} + +def reactNativeRootDir = resolveReactNativeDirectory() +def reactProperties = new Properties() +file("$reactNativeRootDir/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) } + +def reactNativeVersion = reactProperties.getProperty("VERSION_NAME") +def (reactNativeMajorVersion, reactNativeMinorVersion) = reactNativeVersion.split("\\.").collect { it.isInteger() ? it.toInteger() : it } + +def getExtOrDefault(name) { + return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['DatadogSDKReactNativeLogs_' + name] +} + +def getExtOrIntegerDefault(name) { + return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['DatadogSDKReactNativeLogs_' + name]).toInteger() +} + +android { + compileSdkVersion getExtOrIntegerDefault('compileSdkVersion') + buildToolsVersion getExtOrDefault('buildToolsVersion') + def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION + if (agpVersion.tokenize('.')[0].toInteger() >= 7) { + namespace = "com.datadog.reactnative.logs" + } + if (agpVersion.tokenize('.')[0].toInteger() >= 8) { + buildFeatures { + buildConfig = true + } + } + if (agpVersion.tokenize('.')[0].toInteger() < 8) { + compileOptions { + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.majorVersion + } + } + + defaultConfig { + minSdkVersion getExtOrIntegerDefault('minSdkVersion') + targetSdkVersion getExtOrIntegerDefault('targetSdkVersion') + versionCode 1 + versionName "1.0" + buildConfigField("boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()) + } + + sourceSets { + main { + if (isNewArchitectureEnabled()) { + java.srcDirs += ['src/newarch'] + } else { + java.srcDirs += ['src/oldarch'] + } + } + + test { + java.srcDir("src/test/kotlin") + } + } + + testOptions { + unitTests { + returnDefaultValues = true + } + } + + buildTypes { + release { + minifyEnabled false + } + } + lintOptions { + disable 'GradleCompatible' + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } +} + +repositories { + mavenCentral() + google() + maven { url "https://jitpack.io" } + mavenLocal() + + if (reactNativeMajorVersion == 0 && reactNativeMinorVersion < 71) { + def androidSourcesDir = file("$reactNativeRootDir/android") + def androidSourcesName = "React Native sources" + + if (androidSourcesDir.exists()) { + maven { + url androidSourcesDir.toString() + name androidSourcesName + } + } + } +} + +def kotlin_version = getExtOrDefault('kotlinVersion') + +dependencies { + if (reactNativeMajorVersion == 0 && reactNativeMinorVersion < 71) { + // noinspection GradleDynamicVersion + api 'com.facebook.react:react-native:+' + } else { + // We specify the $reactNativeVersion, like it's done on the react-native-gradle-plugin, as the plugin is not applied in tests. + // There is no impact for apps as we apply the same logic: + // https://github.com/facebook/react-native/blob/e1a1e6aa8030bf11d691c3dcf7abd13b25175027/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/DependencyUtils.kt + implementation "com.facebook.react:react-android:$reactNativeVersion" + } + + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + + implementation "com.datadoghq:dd-sdk-android-logs:2.23.0" + implementation "com.datadoghq:dd-sdk-android-internal:2.23.0" + implementation project(path: ':datadog_mobile-react-native') + + testImplementation "org.junit.platform:junit-platform-launcher:1.6.2" + testImplementation "org.junit.jupiter:junit-jupiter-api:5.6.2" + testImplementation "org.junit.jupiter:junit-jupiter-engine:5.6.2" + testImplementation "org.junit.jupiter:junit-jupiter-params:5.6.2" + testImplementation "org.mockito:mockito-junit-jupiter:3.4.6" + testImplementation "org.assertj:assertj-core:3.18.1" + testImplementation "com.github.xgouchet.Elmyr:core:1.3.1" + testImplementation "com.github.xgouchet.Elmyr:inject:1.3.1" + testImplementation "com.github.xgouchet.Elmyr:junit5:1.3.1" + testImplementation "com.github.xgouchet.Elmyr:jvm:1.3.1" + testImplementation "org.mockito.kotlin:mockito-kotlin:5.1.0" + testImplementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + unmock 'org.robolectric:android-all:4.4_r1-robolectric-r2' +} + +tasks.withType(Test) { + useJUnitPlatform { + includeEngines("spek", "junit-jupiter", "junit-vintage") + } + reports { + junitXml.required.set(true) + html.required.set(true) + } +} + +tasks.named("check") { + dependsOn("ktlintCheck") + dependsOn("detekt") +} + +ktlint { + debug.set(false) + android.set(true) + outputToConsole.set(true) + ignoreFailures.set(false) + enableExperimentalRules.set(false) + filter { + exclude("**/generated/**") + include("**/kotlin/**") + } +} + +detekt { + input = files("$projectDir/src/main/kotlin") + config = files("$projectDir/detekt.yml") + reports { + xml { + enabled = true + destination = file("build/reports/detekt.xml") + } + } +} diff --git a/packages/logs/android/detekt.yml b/packages/logs/android/detekt.yml new file mode 100644 index 000000000..c1376f3bf --- /dev/null +++ b/packages/logs/android/detekt.yml @@ -0,0 +1,572 @@ +build: + maxIssues: 0 + weights: + # complexity: 2 + # LongParameterList: 1 + # style: 1 + # comments: 1 + +processors: + active: true + exclude: + # - 'DetektProgressListener' + # - 'FunctionCountProcessor' + # - 'PropertyCountProcessor' + # - 'ClassCountProcessor' + # - 'PackageCountProcessor' + # - 'KtFileCountProcessor' + +console-reports: + active: true + exclude: + # - 'ProjectStatisticsReport' + # - 'ComplexityReport' + # - 'NotificationReport' + # - 'FindingsReport' + - 'FileBasedFindingsReport' + # - 'BuildFailureReport' + +comments: + active: true + CommentOverPrivateFunction: + active: true + CommentOverPrivateProperty: + active: true + EndOfSentenceFormat: + active: true + endOfSentenceFormat: ([.?!][ \t\n\r\f<])|([.?!:]$) + UndocumentedPublicClass: + active: true + excludes: [ "**/test/**","**/androidTest/**","**/*.Test.kt","**/*.Spec.kt","**/*.Spek.kt" ] + searchInNestedClass: true + searchInInnerClass: true + searchInInnerObject: true + searchInInnerInterface: true + UndocumentedPublicFunction: + active: true + excludes: [ "**/test/**","**/androidTest/**","**/*.Test.kt","**/*.Spec.kt","**/*.Spek.kt" ] + UndocumentedPublicProperty: + active: true + excludes: [ "**/test/**","**/androidTest/**","**/*.Test.kt","**/*.Spec.kt","**/*.Spek.kt" ] + +complexity: + active: true + ComplexCondition: + active: true + threshold: 4 + ComplexInterface: + active: true + threshold: 10 + includeStaticDeclarations: false + ComplexMethod: + active: true + threshold: 10 + ignoreSingleWhenExpression: true + ignoreSimpleWhenEntries: true + LabeledExpression: + active: true + ignoredLabels: "" + LargeClass: + active: true + threshold: 600 + LongMethod: + active: true + threshold: 60 + LongParameterList: + active: true + threshold: 6 + ignoreDefaultParameters: true + MethodOverloading: + active: true + threshold: 6 + NestedBlockDepth: + active: true + threshold: 4 + StringLiteralDuplication: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + threshold: 3 + ignoreAnnotation: true + excludeStringsWithLessThan5Characters: true + ignoreStringsRegex: '$^' + TooManyFunctions: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + thresholdInFiles: 11 + thresholdInClasses: 11 + thresholdInInterfaces: 11 + thresholdInObjects: 11 + thresholdInEnums: 11 + ignoreDeprecated: true + ignorePrivate: true + ignoreOverridden: true + +empty-blocks: + active: true + EmptyCatchBlock: + active: true + allowedExceptionNameRegex: "^(_|(ignore|expected).*)" + EmptyClassBlock: + active: true + EmptyDefaultConstructor: + active: true + EmptyDoWhileBlock: + active: true + EmptyElseBlock: + active: true + EmptyFinallyBlock: + active: true + EmptyForBlock: + active: true + EmptyFunctionBlock: + active: true + ignoreOverridden: true + EmptyIfBlock: + active: true + EmptyInitBlock: + active: true + EmptyKtFile: + active: true + EmptySecondaryConstructor: + active: true + EmptyWhenBlock: + active: true + EmptyWhileBlock: + active: true + +exceptions: + active: true + ExceptionRaisedInUnexpectedLocation: + active: true + methodNames: 'toString,hashCode,equals,finalize' + InstanceOfCheckForException: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + NotImplementedDeclaration: + active: true + PrintStackTrace: + active: true + RethrowCaughtException: + active: true + ReturnFromFinally: + active: true + ignoreLabeled: true + SwallowedException: + active: true + ignoredExceptionTypes: 'InterruptedException,NumberFormatException,ParseException,MalformedURLException' + allowedExceptionNameRegex: "^(_|(ignore|expected).*)" + ThrowingExceptionFromFinally: + active: true + ThrowingExceptionInMain: + active: true + ThrowingExceptionsWithoutMessageOrCause: + active: true + exceptions: 'IllegalArgumentException,IllegalStateException,IOException' + ThrowingNewInstanceOfSameException: + active: true + TooGenericExceptionCaught: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + exceptionNames: + - ArrayIndexOutOfBoundsException + - Error + - Exception + - IllegalMonitorStateException + - NullPointerException + - IndexOutOfBoundsException + - RuntimeException + - Throwable + allowedExceptionNameRegex: "^(_|(ignore|expected).*)" + TooGenericExceptionThrown: + active: true + exceptionNames: + - Error + - Exception + - Throwable + - RuntimeException + +formatting: + active: false + android: false + autoCorrect: true + AnnotationOnSeparateLine: + active: true + autoCorrect: true + ChainWrapping: + active: true + autoCorrect: true + CommentSpacing: + active: true + autoCorrect: true + Filename: + active: true + FinalNewline: + active: true + autoCorrect: true + ImportOrdering: + active: true + autoCorrect: true + Indentation: + active: true + autoCorrect: true + indentSize: 4 + continuationIndentSize: 4 + MaximumLineLength: + active: true + maxLineLength: 120 + ModifierOrdering: + active: true + autoCorrect: true + MultiLineIfElse: + active: true + autoCorrect: true + NoBlankLineBeforeRbrace: + active: true + autoCorrect: true + NoConsecutiveBlankLines: + active: true + autoCorrect: true + NoEmptyClassBody: + active: true + autoCorrect: true + NoLineBreakAfterElse: + active: true + autoCorrect: true + NoLineBreakBeforeAssignment: + active: true + autoCorrect: true + NoMultipleSpaces: + active: true + autoCorrect: true + NoSemicolons: + active: true + autoCorrect: true + NoTrailingSpaces: + active: true + autoCorrect: true + NoUnitReturn: + active: true + autoCorrect: true + NoUnusedImports: + active: true + autoCorrect: true + NoWildcardImports: + active: true + autoCorrect: true + PackageName: + active: true + autoCorrect: true + ParameterListWrapping: + active: true + autoCorrect: true + indentSize: 4 + SpacingAroundColon: + active: true + autoCorrect: true + SpacingAroundComma: + active: true + autoCorrect: true + SpacingAroundCurly: + active: true + autoCorrect: true + SpacingAroundDot: + active: true + autoCorrect: true + SpacingAroundKeyword: + active: true + autoCorrect: true + SpacingAroundOperators: + active: true + autoCorrect: true + SpacingAroundParens: + active: true + autoCorrect: true + SpacingAroundRangeOperator: + active: true + autoCorrect: true + StringTemplate: + active: true + autoCorrect: true + +naming: + active: true + ClassNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + classPattern: '[A-Z$][a-zA-Z0-9$]*' + ConstructorParameterNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + parameterPattern: '[a-z][A-Za-z0-9]*' + privateParameterPattern: '[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + EnumNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + enumEntryPattern: '^[A-Z][_a-zA-Z0-9]*' + ForbiddenClassName: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + forbiddenName: '' + FunctionMaxLength: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + maximumFunctionNameLength: 30 + FunctionMinLength: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + minimumFunctionNameLength: 3 + FunctionNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + functionPattern: '^([a-z$][a-zA-Z$0-9]*)|(`.*`)$' + excludeClassPattern: '$^' + ignoreOverridden: true + FunctionParameterNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + parameterPattern: '[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + InvalidPackageDeclaration: + active: true + rootPackage: '' + MatchingDeclarationName: + active: true + MemberNameEqualsClassName: + active: true + ignoreOverridden: true + ObjectPropertyNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + constantPattern: '[A-Za-z][_A-Za-z0-9]*' + propertyPattern: '[A-Za-z][_A-Za-z0-9]*' + privatePropertyPattern: '(_)?[A-Za-z][_A-Za-z0-9]*' + PackageNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + packagePattern: '^[a-z]+(\.[a-z][A-Za-z0-9]*)*$' + TopLevelPropertyNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + constantPattern: '[A-Z][_A-Z0-9]*' + propertyPattern: '[A-Za-z][_A-Za-z0-9]*' + privatePropertyPattern: '_?[A-Za-z][_A-Za-z0-9]*' + VariableMaxLength: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + maximumVariableNameLength: 64 + VariableMinLength: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + minimumVariableNameLength: 1 + VariableNaming: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + variablePattern: '[a-z][A-Za-z0-9]*' + privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + +performance: + active: true + ArrayPrimitive: + active: true + ForEachOnRange: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + SpreadOperator: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + UnnecessaryTemporaryInstantiation: + active: true + +potential-bugs: + active: true + Deprecation: + active: true + DuplicateCaseInWhenExpression: + active: true + EqualsAlwaysReturnsTrueOrFalse: + active: true + EqualsWithHashCodeExist: + active: true + ExplicitGarbageCollectionCall: + active: true + HasPlatformType: + active: true + InvalidRange: + active: true + IteratorHasNextCallsNextMethod: + active: true + IteratorNotThrowingNoSuchElementException: + active: true + LateinitUsage: + active: false + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + excludeAnnotatedProperties: "" + ignoreOnClassesPattern: "" + MissingWhenCase: + active: true + RedundantElseInWhen: + active: true + UnconditionalJumpStatementInLoop: + active: true + UnreachableCode: + active: true + UnsafeCallOnNullableType: + active: true + UnsafeCast: + active: true + UselessPostfixExpression: + active: true + WrongEqualsTypeParameter: + active: true + +style: + active: false + CollapsibleIfStatements: + active: true + DataClassContainsFunctions: + active: true + conversionFunctionPrefix: 'to' + DataClassShouldBeImmutable: + active: true + EqualsNullCall: + active: true + EqualsOnSignatureLine: + active: true + ExplicitItLambdaParameter: + active: true + ExpressionBodySyntax: + active: false + includeLineWrapping: false + ForbiddenComment: + active: true + values: 'TODO:,FIXME:,STOPSHIP:' + allowedPatterns: "" + ForbiddenImport: + active: true + imports: '' + forbiddenPatterns: "" + ForbiddenVoid: + active: true + ignoreOverridden: false + ignoreUsageInGenerics: true + FunctionOnlyReturningConstant: + active: true + ignoreOverridableFunction: true + excludedFunctions: 'describeContents' + excludeAnnotatedFunction: "dagger.Provides" + LibraryCodeMustSpecifyReturnType: + active: true + LoopWithTooManyJumpStatements: + active: true + maxJumpCount: 1 + MagicNumber: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + ignoreNumbers: '-1,0,1,2' + ignoreHashCodeFunction: true + ignorePropertyDeclaration: false + ignoreConstantDeclaration: true + ignoreCompanionObjectPropertyDeclaration: true + ignoreAnnotation: false + ignoreNamedArgument: true + ignoreEnums: false + ignoreRanges: false + MandatoryBracesIfStatements: + active: true + MaxLineLength: + active: true + maxLineLength: 120 + excludePackageStatements: true + excludeImportStatements: true + excludeCommentStatements: false + MayBeConst: + active: true + ModifierOrder: + active: true + NestedClassesVisibility: + active: true + NewLineAtEndOfFile: + active: false + NoTabs: + active: true + OptionalAbstractKeyword: + active: true + OptionalUnit: + active: true + OptionalWhenBraces: + active: true + PreferToOverPairSyntax: + active: true + ProtectedMemberInFinalClass: + active: true + RedundantExplicitType: + active: true + RedundantVisibilityModifierRule: + active: true + ReturnCount: + active: true + max: 2 + excludedFunctions: "equals" + excludeLabeled: false + excludeReturnFromLambda: true + excludeGuardClauses: true + SafeCast: + active: true + SerialVersionUIDInSerializableClass: + active: true + SpacingBetweenPackageAndImports: + active: true + ThrowsCount: + active: true + max: 2 + TrailingWhitespace: + active: true + UnderscoresInNumericLiterals: + active: true + acceptableDecimalLength: 5 + UnnecessaryAbstractClass: + active: true + excludeAnnotatedClasses: "dagger.Module" + UnnecessaryApply: + active: true + UnnecessaryInheritance: + active: true + UnnecessaryLet: + active: true + UnnecessaryParentheses: + active: true + UntilInsteadOfRangeTo: + active: true + UnusedImports: + active: true + UnusedPrivateClass: + active: true + UnusedPrivateMember: + active: true + allowedNames: "(_|ignored|expected|serialVersionUID)" + UseArrayLiteralsInAnnotations: + active: true + UseCheckOrError: + active: true + UseDataClass: + active: true + excludeAnnotatedClasses: "" + allowVars: true + UseIfInsteadOfWhen: + active: true + UseRequire: + active: true + UselessCallOnNotNull: + active: true + UtilityClassWithPublicConstructor: + active: true + VarCouldBeVal: + active: true + WildcardImport: + active: true + excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" + excludeImports: 'java.util.*,kotlinx.android.synthetic.*' diff --git a/packages/logs/android/gradle.properties b/packages/logs/android/gradle.properties new file mode 100644 index 000000000..bf93dff96 --- /dev/null +++ b/packages/logs/android/gradle.properties @@ -0,0 +1,6 @@ +DatadogSdkReactNativeLogs_kotlinVersion=1.8.21 +DatadogSdkReactNativeLogs_minSdkVersion=21 +DatadogSdkReactNativeLogs_compileSdkVersion=33 +DatadogSdkReactNativeLogs_buildToolsVersion=33.0.0 +DatadogSdkReactNativeLogs_targetSdkVersion=33 +android.useAndroidX=true diff --git a/packages/logs/android/gradle/wrapper/gradle-wrapper.jar b/packages/logs/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..249e5832f Binary files /dev/null and b/packages/logs/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/packages/logs/android/gradle/wrapper/gradle-wrapper.properties b/packages/logs/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..27313fbc8 --- /dev/null +++ b/packages/logs/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/logs/android/gradlew b/packages/logs/android/gradlew new file mode 100755 index 000000000..a69d9cb6c --- /dev/null +++ b/packages/logs/android/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/packages/logs/android/gradlew.bat b/packages/logs/android/gradlew.bat new file mode 100644 index 000000000..f127cfd49 --- /dev/null +++ b/packages/logs/android/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/logs/android/settings.gradle b/packages/logs/android/settings.gradle new file mode 100644 index 000000000..e48af6b4d --- /dev/null +++ b/packages/logs/android/settings.gradle @@ -0,0 +1,4 @@ +// This is only used for building locally and testing the package. +// If the package is used in an app that contains ":datadog_mobile-react-native" it will be resolved correctly. +include ':datadog_mobile-react-native' +project(':datadog_mobile-react-native').projectDir = new File('../../core/android') diff --git a/packages/logs/android/src/main/AndroidManifest.xml b/packages/logs/android/src/main/AndroidManifest.xml new file mode 100644 index 000000000..99eb8c827 --- /dev/null +++ b/packages/logs/android/src/main/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdLogsImplementation.kt b/packages/logs/android/src/main/kotlin/com/datadog/reactnative/logs/DdLogsImplementation.kt similarity index 86% rename from packages/core/android/src/main/kotlin/com/datadog/reactnative/DdLogsImplementation.kt rename to packages/logs/android/src/main/kotlin/com/datadog/reactnative/logs/DdLogsImplementation.kt index 7223a2c72..c8fb12581 100644 --- a/packages/core/android/src/main/kotlin/com/datadog/reactnative/DdLogsImplementation.kt +++ b/packages/logs/android/src/main/kotlin/com/datadog/reactnative/logs/DdLogsImplementation.kt @@ -4,10 +4,18 @@ * Copyright 2016-Present Datadog, Inc. */ -package com.datadog.reactnative +package com.datadog.reactnative.logs +import com.datadog.android.Datadog import android.util.Log as AndroidLog import com.datadog.android.log.Logger +import com.datadog.android.log.Logs +import com.datadog.android.log.LogsConfiguration +import com.datadog.reactnative.DatadogWrapper +import com.datadog.reactnative.DatadogSDKWrapper +import com.datadog.reactnative.DatadogSDKWrapperStorage +import com.datadog.reactnative.GlobalState +import com.datadog.reactnative.asCustomEndpoints import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReadableMap @@ -22,7 +30,7 @@ class DdLogsImplementation( val bundleLogsWithRum = datadog.bundleLogsWithRum val bundleLogsWithTraces = datadog.bundleLogsWithTraces - logger ?: Logger.Builder(DatadogSDKWrapperStorage.getSdkCore()) + logger ?: Logger.Builder(Datadog.getInstance()) .setLogcatLogsEnabled(true) .setBundleWithRumEnabled(bundleLogsWithRum) .setBundleWithTraceEnabled(bundleLogsWithTraces) @@ -30,6 +38,18 @@ class DdLogsImplementation( .build() } + /** + * Enables DdLogs + * @param configuration The logs configuration. + */ + fun enable(configuration: ReadableMap, promise: Promise) { + val logsConfiguration = buildLogsConfiguration(configuration) + + Logs.enable(logsConfiguration, DatadogSDKWrapperStorage.getSdkCore()) + + promise.resolve(null) + } + /** * Send a log with Debug level. * @param message The message to send. @@ -226,6 +246,16 @@ class DdLogsImplementation( promise.resolve(null) } + private fun buildLogsConfiguration(configuration: ReadableMap): LogsConfiguration { + val configBuilder = LogsConfiguration.Builder() + val customEndpoints = configuration.getMap("customEndpoints")?.asCustomEndpoints() + customEndpoints?.logs?.let { + configBuilder.useCustomEndpoint(it) + } + + return configBuilder.build() + } + companion object { private const val SDK_NOT_INITIALIZED_MESSAGE = "DD_INTERNAL_LOG_SENT_BEFORE_SDK_INIT" internal const val NAME = "DdLogs" diff --git a/packages/logs/android/src/main/kotlin/com/datadog/reactnative/logs/DdSdkReactNativeLogsPackage.kt b/packages/logs/android/src/main/kotlin/com/datadog/reactnative/logs/DdSdkReactNativeLogsPackage.kt new file mode 100644 index 000000000..8959803c4 --- /dev/null +++ b/packages/logs/android/src/main/kotlin/com/datadog/reactnative/logs/DdSdkReactNativeLogsPackage.kt @@ -0,0 +1,49 @@ +/* + * 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 2016-Present Datadog, Inc. + */ + +package com.datadog.reactnative.logs + +import com.datadog.reactnative.DatadogSDKWrapper +import com.facebook.react.TurboReactPackage +import com.facebook.react.bridge.LifecycleEventListener +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.module.model.ReactModuleInfo +import com.facebook.react.module.model.ReactModuleInfoProvider + +/** + * Package of native dd-sdk-reactnative native modules. + */ +class DdSdkReactNativeLogsPackage : TurboReactPackage() { + private val sdkWrapper = DatadogSDKWrapper() + override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? { + return when (name) { + DdLogsImplementation.NAME -> DdLogs(reactContext, sdkWrapper) + else -> null + } + } + + override fun getReactModuleInfoProvider(): ReactModuleInfoProvider { + return ReactModuleInfoProvider { + val isTurboModule: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED + val moduleInfos = listOf( + DdLogsImplementation.NAME, + ).associateWith { + ReactModuleInfo( + it, + it, + false, // canOverrideExistingModule + false, // needsEagerInit + true, // hasConstants + false, // isCxxModule + isTurboModule // isTurboModule + ) + } + + moduleInfos + } + } +} diff --git a/packages/core/android/src/newarch/kotlin/com/datadog/reactnative/DdLogs.kt b/packages/logs/android/src/newarch/kotlin/com/datadog/reactnative/logs/DdLogs.kt similarity index 94% rename from packages/core/android/src/newarch/kotlin/com/datadog/reactnative/DdLogs.kt rename to packages/logs/android/src/newarch/kotlin/com/datadog/reactnative/logs/DdLogs.kt index a9408e227..c59d87262 100644 --- a/packages/core/android/src/newarch/kotlin/com/datadog/reactnative/DdLogs.kt +++ b/packages/logs/android/src/newarch/kotlin/com/datadog/reactnative/logs/DdLogs.kt @@ -4,7 +4,7 @@ * Copyright 2016-Present Datadog, Inc. */ -package com.datadog.reactnative +package com.datadog.reactnative.logs import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext @@ -23,6 +23,15 @@ class DdLogs( override fun getName(): String = DdLogsImplementation.NAME + /** + * Enables DdLogs + * @param configuration The logs configuration. + */ + @ReactMethod + override fun enable(configuration: ReadableMap, promise: Promise) { + implementation.enable(configuration, promise) + } + /** * Send a log with Debug level. * @param message The message to send. diff --git a/packages/core/android/src/oldarch/kotlin/com/datadog/reactnative/DdLogs.kt b/packages/logs/android/src/oldarch/kotlin/com/datadog/reactnative/logs/DdLogs.kt similarity index 93% rename from packages/core/android/src/oldarch/kotlin/com/datadog/reactnative/DdLogs.kt rename to packages/logs/android/src/oldarch/kotlin/com/datadog/reactnative/logs/DdLogs.kt index cc3ee410d..e845e73a0 100644 --- a/packages/core/android/src/oldarch/kotlin/com/datadog/reactnative/DdLogs.kt +++ b/packages/logs/android/src/oldarch/kotlin/com/datadog/reactnative/logs/DdLogs.kt @@ -4,8 +4,10 @@ * Copyright 2016-Present Datadog, Inc. */ -package com.datadog.reactnative +package com.datadog.reactnative.logs +import com.datadog.reactnative.DatadogSDKWrapper +import com.datadog.reactnative.DatadogWrapper import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule @@ -24,6 +26,15 @@ class DdLogs( override fun getName(): String = DdLogsImplementation.NAME + /** + * Enables DdLogs + * @param configuration The logs configuration. + */ + @ReactMethod + fun enable(configuration: ReadableMap, promise: Promise) { + implementation.enable(configuration, promise) + } + /** * Send a log with Debug level. * @param message The message to send. diff --git a/packages/logs/babel.config.js b/packages/logs/babel.config.js new file mode 100644 index 000000000..990d54137 --- /dev/null +++ b/packages/logs/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: ['module:@react-native/babel-preset'] +}; diff --git a/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.pbxproj b/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.pbxproj new file mode 100644 index 000000000..c8de4526e --- /dev/null +++ b/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.pbxproj @@ -0,0 +1,272 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXCopyFilesBuildPhase section */ + 58B511D91A9E6C8500147676 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "include/$(PRODUCT_NAME)"; + dstSubfolderSpec = 16; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 134814201AA4EA6300B7C361 /* libDdSdkReactNativeLogs.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libDdSdkReactNativeLogs.a; sourceTree = BUILT_PRODUCTS_DIR; }; + F625545A26A82D430033052D /* Sources */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Sources; sourceTree = ""; }; + F625545B26A82D430033052D /* Tests */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Tests; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 58B511D81A9E6C8500147676 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 134814211AA4EA7D00B7C361 /* Products */ = { + isa = PBXGroup; + children = ( + 134814201AA4EA6300B7C361 /* libDdSdkReactNativeLogs.a */, + ); + name = Products; + sourceTree = ""; + }; + 58B511D21A9E6C8500147676 = { + isa = PBXGroup; + children = ( + F625545A26A82D430033052D /* Sources */, + F625545B26A82D430033052D /* Tests */, + 134814211AA4EA7D00B7C361 /* Products */, + ); + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 58B511DA1A9E6C8500147676 /* DdSdkReactNativeLogs */ = { + isa = PBXNativeTarget; + buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "DdSdkReactNativeLogs" */; + buildPhases = ( + 58B511D71A9E6C8500147676 /* Sources */, + 58B511D81A9E6C8500147676 /* Frameworks */, + 58B511D91A9E6C8500147676 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = DdSdkReactNativeLogs; + productName = RCTDataManager; + productReference = 134814201AA4EA6300B7C361 /* libDdSdkReactNativeLogs.a */; + productType = "com.apple.product-type.library.static"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 58B511D31A9E6C8500147676 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0920; + ORGANIZATIONNAME = Facebook; + TargetAttributes = { + 58B511DA1A9E6C8500147676 = { + CreatedOnToolsVersion = 6.1.1; + }; + }; + }; + buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "DdSdkReactNativeLogs" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + English, + en, + ); + mainGroup = 58B511D21A9E6C8500147676; + productRefGroup = 58B511D21A9E6C8500147676; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 58B511DA1A9E6C8500147676 /* DdSdkReactNativeLogs */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 58B511D71A9E6C8500147676 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 58B511ED1A9E6C8500147676 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + }; + name = Debug; + }; + 58B511EE1A9E6C8500147676 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 58B511F01A9E6C8500147676 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + HEADER_SEARCH_PATHS = ( + "$(inherited)", + /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, + "$(SRCROOT)/../../../React/**", + "$(SRCROOT)/../../react-native/React/**", + ); + LIBRARY_SEARCH_PATHS = "$(inherited)"; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = DdSdkReactNativeLogs; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "DdSdkReactNativeLogs-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 58B511F11A9E6C8500147676 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + HEADER_SEARCH_PATHS = ( + "$(inherited)", + /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, + "$(SRCROOT)/../../../React/**", + "$(SRCROOT)/../../react-native/React/**", + ); + LIBRARY_SEARCH_PATHS = "$(inherited)"; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = DdSdkReactNativeLogs; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "DdSdkReactNativeLogs-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "DdSdkReactNativeLogs" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 58B511ED1A9E6C8500147676 /* Debug */, + 58B511EE1A9E6C8500147676 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "DdSdkReactNativeLogs" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 58B511F01A9E6C8500147676 /* Debug */, + 58B511F11A9E6C8500147676 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 58B511D31A9E6C8500147676 /* Project object */; +} diff --git a/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..94b2795e2 --- /dev/null +++ b/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,4 @@ + + + diff --git a/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/packages/logs/ios/DdSdkReactNativeLogs.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/logs/ios/Sources/DatadogSDKReactNativeLogs.h b/packages/logs/ios/Sources/DatadogSDKReactNativeLogs.h new file mode 100644 index 000000000..3953fc4d2 --- /dev/null +++ b/packages/logs/ios/Sources/DatadogSDKReactNativeLogs.h @@ -0,0 +1,8 @@ +/* + * 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 2016-Present Datadog, Inc. + */ + +// This file is imported in the auto-generated DatadogSDKReactNativeLogs-Swift.h header file. +// Deleting it could result in iOS builds failing. diff --git a/packages/core/ios/Sources/DdLogs.h b/packages/logs/ios/Sources/DdLogs.h similarity index 91% rename from packages/core/ios/Sources/DdLogs.h rename to packages/logs/ios/Sources/DdLogs.h index 62db1ead2..e9e32ddda 100644 --- a/packages/core/ios/Sources/DdLogs.h +++ b/packages/logs/ios/Sources/DdLogs.h @@ -9,7 +9,7 @@ #ifdef RCT_NEW_ARCH_ENABLED -#import +#import @interface DdLogs: NSObject #else diff --git a/packages/core/ios/Sources/DdLogs.mm b/packages/logs/ios/Sources/DdLogs.mm similarity index 90% rename from packages/core/ios/Sources/DdLogs.mm rename to packages/logs/ios/Sources/DdLogs.mm index 6cc530d8d..a3b0682bb 100644 --- a/packages/core/ios/Sources/DdLogs.mm +++ b/packages/logs/ios/Sources/DdLogs.mm @@ -4,18 +4,25 @@ * Copyright 2016-Present Datadog, Inc. */ // Import this first to prevent require cycles -#if __has_include("DatadogSDKReactNative-Swift.h") -#import +#if __has_include("DatadogSDKReactNativeLogs-Swift.h") +#import #else -#import +#import #endif #import "DdLogs.h" - +#import @implementation DdLogs RCT_EXPORT_MODULE() +RCT_REMAP_METHOD(enable, withConfiguration:(NSDictionary*)configuration + withResolver:(RCTPromiseResolveBlock)resolve + withRejecter:(RCTPromiseRejectBlock)reject) +{ + [self enable:configuration resolve:resolve reject:reject]; +} + RCT_REMAP_METHOD(debug, withDebugMessage:(NSString*)message withContext:(NSDictionary*)context withResolver:(RCTPromiseResolveBlock)resolve @@ -114,9 +121,12 @@ + (BOOL)requiresMainQueueSetup { } - (dispatch_queue_t)methodQueue { - return [RNQueue getSharedQueue]; + return [RNQueueHolderProxy getSharedQueue]; } +- (void)enable:(NSDictionary *)configuration resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { + [self.ddLogsImplementation enableWithConfiguration:configuration resolve:resolve reject:reject]; +} - (void)debug:(NSString *)message context:(NSDictionary *)context resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject { [self.ddLogsImplementation debugWithMessage:message context:context resolve:resolve reject:reject]; diff --git a/packages/core/ios/Sources/DdLogsImplementation.swift b/packages/logs/ios/Sources/DdLogsImplementation.swift similarity index 77% rename from packages/core/ios/Sources/DdLogsImplementation.swift rename to packages/logs/ios/Sources/DdLogsImplementation.swift index 264a3d0b3..ce89a8286 100644 --- a/packages/core/ios/Sources/DdLogsImplementation.swift +++ b/packages/logs/ios/Sources/DdLogsImplementation.swift @@ -6,21 +6,24 @@ import Foundation import DatadogLogs +import DatadogCore +import DatadogInternal +import DatadogSDKReactNative @objc public class DdLogsImplementation: NSObject { private lazy var logger: LoggerProtocol = loggerProvider() - private let loggerProvider: () -> LoggerProtocol - private let isSDKInitialized: () -> Bool + private lazy var loggerProvider: () -> LoggerProtocol = { self.createLogger() }; + private lazy var isSDKInitialized: () -> Bool = { DatadogSDKWrapper.shared.isInitialized() }; + private lazy var loggerConfiguration = DatadogLogs.Logger.Configuration() - internal init(_ loggerProvider: @escaping () -> LoggerProtocol, _ isSDKInitialized: @escaping () -> Bool) { - self.loggerProvider = loggerProvider - self.isSDKInitialized = isSDKInitialized - } - @objc - public override convenience init() { - self.init({ DatadogSDKWrapper.shared.createLogger() }, { DatadogSDKWrapper.shared.isInitialized() }) + public func enable(configuration: NSDictionary, resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) -> Void { + let logsConfiguration = configuration.asDdSdkConfiguration() + let logsConfig = buildLogsConfiguration(configuration: logsConfiguration) + let core = Datadog.sdkInstance(named: CoreRegistry.defaultInstanceName) + Logs.enable(with: logsConfig, in: core) + resolve(nil) } @objc @@ -110,6 +113,24 @@ public class DdLogsImplementation: NSObject { logger._internal.log(level: .error, message: message, errorKind: errorKind, errorMessage: errorMessage, stackTrace: stacktrace, attributes: attributes) resolve(nil) } + + internal func buildLogsConfiguration(configuration: DdSdkConfiguration) -> Logs.Configuration { + var customLogsEndpointURL: URL? = nil + if let customLogsEndpoint = configuration.customEndpoints?.logs as? NSString { + if (customLogsEndpoint != "") { + customLogsEndpointURL = URL(string: "\(customLogsEndpoint)/api/v2/logs" as String) + } + } + + return Logs.Configuration(customEndpoint: customLogsEndpointURL) + } + + internal func createLogger() -> LoggerProtocol { +// let core = DatadogSDKWrapper.shared.getCoreInstanceOrDefault() + let core = Datadog.sdkInstance(named: CoreRegistry.defaultInstanceName) + return DatadogLogs.Logger.create(with: loggerConfiguration, in: core) + } + } internal extension DatadogLogs.Logger.Configuration { diff --git a/packages/logs/package.json b/packages/logs/package.json new file mode 100644 index 000000000..71192f4b7 --- /dev/null +++ b/packages/logs/package.json @@ -0,0 +1,96 @@ +{ + "name": "@datadog/mobile-react-native-logs", + "version": "2.11.0", + "description": "A client-side React Native module to enable Log tracking with Datadog", + "keywords": [ + "datadog", + "react-native", + "ios", + "android" + ], + "author": "Datadog (https://github.com/DataDog)", + "homepage": "https://github.com/DataDog/dd-sdk-reactnative#readme", + "repository": "https://github.com/DataDog/dd-sdk-reactnative", + "bugs": { + "url": "https://github.com/DataDog/dd-sdk-reactnative/issues" + }, + "license": "Apache-2.0", + "main": "lib/commonjs/index", + "files": [ + "src/**", + "lib/**", + "scripts/**", + "android/build.gradle", + "android/detekt.yml", + "android/gradle.properties", + "android/src/**", + "ios/Sources/**", + "ios/DatadogSDKReactNativeLogs.xcodeproj/project.xcworkspace/xcsharedata", + "ios/DatadogSDKReactNativeLogs.xcodeproj/project.xcworkspace/*.xcworkspacedata", + "ios/DatadogSDKReactNativeLogs.xcodeproj/*.pbxproj", + "DatadogSDKReactNativeLogs.podspec" + ], + "types": "lib/typescript/index.d.ts", + "react-native": "src/index", + "source": "src", + "module": "lib/module/index", + "publishConfig": { + "access": "public" + }, + "scripts": { + "test": "jest", + "lint": "eslint .", + "prepare": "rm -rf lib && yarn bob build" + }, + "dependencies": { + "@datadog/mobile-react-native": "workspace:packages/core" + }, + "peerDependencies": { + "@datadog/mobile-react-native": "workspace:packages/core", + "react": ">=16.13.1", + "react-native": ">=0.63.4 <1.0" + }, + "devDependencies": { + "@datadog/mobile-react-native": "workspace:packages/core", + "@testing-library/react-native": "7.0.2", + "react-native-builder-bob": "0.26.0" + }, + "jest": { + "preset": "react-native", + "moduleNameMapper": { + "@datadog/mobile-react-native": "../core/src" + }, + "modulePathIgnorePatterns": [ + "/lib/" + ], + "setupFiles": [ + "./../../node_modules/react-native-gesture-handler/jestSetup.js", + "./../../jest.setup.js" + ], + "transformIgnorePatterns": [ + "jest-runner" + ] + }, + "react-native-builder-bob": { + "source": "src", + "output": "lib", + "targets": [ + "commonjs", + "module", + [ + "typescript", + { + "tsc": "./../../node_modules/.bin/tsc" + } + ] + ] + }, + "codegenConfig": { + "name": "DdLogs", + "type": "all", + "jsSrcsDir": "./src/specs", + "android": { + "javaPackageName": "com.datadog.reactnative.logs" + } + } +} diff --git a/packages/core/src/logs/DdLogs.ts b/packages/logs/src/DdLogs.ts similarity index 78% rename from packages/core/src/logs/DdLogs.ts rename to packages/logs/src/DdLogs.ts index 9ac35fa73..3ea170708 100644 --- a/packages/core/src/logs/DdLogs.ts +++ b/packages/logs/src/DdLogs.ts @@ -4,14 +4,20 @@ * Copyright 2016-Present Datadog, Inc. */ -import { DATADOG_MESSAGE_PREFIX, InternalLog } from '../InternalLog'; -import { SdkVerbosity } from '../SdkVerbosity'; -import type { DdNativeLogsType } from '../nativeModulesTypes'; -import { DdAttributes } from '../rum/DdAttributes'; -import type { ErrorSource } from '../rum/types'; -import { validateContext } from '../utils/argsUtils'; +import type { + DdSdkReactNativeConfiguration, + ErrorSource +} from '@datadog/mobile-react-native'; +import { + SdkVerbosity, + DATADOG_MESSAGE_PREFIX, + InternalLog, + DdAttributes, + validateContext +} from '@datadog/mobile-react-native'; import { generateEventMapper } from './eventMapper'; +import type { Spec as DdNativeLogsType } from './specs/NativeDdLogs'; import type { DdLogsType, LogArguments, @@ -43,11 +49,30 @@ const isLogWithError = ( class DdLogsWrapper implements DdLogsType { // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires - private nativeLogs: DdNativeLogsType = require('../specs/NativeDdLogs') + private nativeLogs: DdNativeLogsType = require('./specs/NativeDdLogs') .default; private logEventMapper = generateEventMapper(undefined); + private isEnabled = false; + + enable = ( + configuration: Partial + ): Promise => { + console.log('DDLOGS ENABLE', configuration); + if (configuration.logEventMapper) { + DdLogs.registerLogEventMapper(configuration.logEventMapper); + } + + this.isEnabled = true; + return this.nativeLogs.enable(configuration); + }; debug = (...args: LogArguments | LogWithErrorArguments): Promise => { + if (!this.isEnabled) { + console.log( + 'DdLogs is not enabled yet. Please call enable() before sending any logs.' + ); + return Promise.resolve(undefined); + } if (isLogWithError(args)) { return this.logWithError( args[0], @@ -63,6 +88,12 @@ class DdLogsWrapper implements DdLogsType { }; info = (...args: LogArguments | LogWithErrorArguments): Promise => { + if (!this.isEnabled) { + console.log( + 'DdLogs is not enabled yet. Please call enable() before sending any logs.' + ); + return Promise.resolve(undefined); + } if (isLogWithError(args)) { return this.logWithError( args[0], @@ -78,6 +109,12 @@ class DdLogsWrapper implements DdLogsType { }; warn = (...args: LogArguments | LogWithErrorArguments): Promise => { + if (!this.isEnabled) { + console.log( + 'DdLogs is not enabled yet. Please call enable() before sending any logs.' + ); + return Promise.resolve(undefined); + } if (isLogWithError(args)) { return this.logWithError( args[0], @@ -93,6 +130,12 @@ class DdLogsWrapper implements DdLogsType { }; error = (...args: LogArguments | LogWithErrorArguments): Promise => { + if (!this.isEnabled) { + console.log( + 'DdLogs is not enabled yet. Please call enable() before sending any logs.' + ); + return Promise.resolve(undefined); + } if (isLogWithError(args)) { return this.logWithError( args[0], @@ -240,4 +283,10 @@ class DdLogsWrapper implements DdLogsType { } } -export const DdLogs = new DdLogsWrapper(); +const LOGS_SYMBOL = Symbol.for('com.datadog.reactnative.logs'); + +if (!Object.getOwnPropertySymbols(globalThis).includes(LOGS_SYMBOL)) { + globalThis[LOGS_SYMBOL] = new DdLogsWrapper(); +} + +export const DdLogs = globalThis[LOGS_SYMBOL] as DdLogsWrapper; diff --git a/packages/core/src/logs/eventMapper.ts b/packages/logs/src/eventMapper.ts similarity index 71% rename from packages/core/src/logs/eventMapper.ts rename to packages/logs/src/eventMapper.ts index 2bbd398cb..613fbc58f 100644 --- a/packages/core/src/logs/eventMapper.ts +++ b/packages/logs/src/eventMapper.ts @@ -4,9 +4,8 @@ * Copyright 2016-Present Datadog, Inc. */ -import type { Attributes } from '../sdk/AttributesSingleton/types'; -import { EventMapper } from '../sdk/EventMappers/EventMapper'; -import type { UserInfo } from '../sdk/UserInfoSingleton/types'; +import type { AdditionalEventDataForMapper } from '@datadog/mobile-react-native'; +import { EventMapper } from '@datadog/mobile-react-native'; import type { LogEvent, @@ -31,24 +30,28 @@ export const formatRawLogToNativeEvent = ( export const formatRawLogToLogEvent = ( rawLog: RawLog | RawLogWithError, - additionalInformation: { - userInfo: UserInfo; - attributes: Attributes; - } + additionalInformation: AdditionalEventDataForMapper ): LogEvent => { + const userInfo = { + ...additionalInformation.userInfo, + id: additionalInformation.userInfo.id ?? '' + }; + return { ...rawLog, - userInfo: additionalInformation.userInfo, + userInfo, attributes: additionalInformation.attributes }; }; export const generateEventMapper = ( logEventMapper: LogEventMapper | undefined -) => - new EventMapper( +) => { + console.log('generateEventMapper', EventMapper); + return new EventMapper( logEventMapper, formatRawLogToLogEvent, formatLogEventToNativeLog, formatRawLogToNativeEvent ); +}; diff --git a/packages/logs/src/index.tsx b/packages/logs/src/index.tsx new file mode 100644 index 000000000..78053986a --- /dev/null +++ b/packages/logs/src/index.tsx @@ -0,0 +1,10 @@ +/* + * 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 2016-Present Datadog, Inc. + */ +import { DdLogs } from './DdLogs'; +import type { DdLogsType } from './types'; + +export { DdLogs }; +export type { DdLogsType }; diff --git a/packages/core/src/specs/NativeDdLogs.ts b/packages/logs/src/specs/NativeDdLogs.ts similarity index 96% rename from packages/core/src/specs/NativeDdLogs.ts rename to packages/logs/src/specs/NativeDdLogs.ts index f1a60f4c7..c12027121 100644 --- a/packages/core/src/specs/NativeDdLogs.ts +++ b/packages/logs/src/specs/NativeDdLogs.ts @@ -14,6 +14,12 @@ import { TurboModuleRegistry } from 'react-native'; export interface Spec extends TurboModule { readonly getConstants: () => {}; + /** + * Enables Logs + * @param configuration: Logs configuration + */ + readonly enable: (configuration: Object) => Promise; + /** * Send a log with DEBUG level. * @param message: The message to send. diff --git a/packages/core/src/logs/types.ts b/packages/logs/src/types.ts similarity index 92% rename from packages/core/src/logs/types.ts rename to packages/logs/src/types.ts index 9c1b3cb09..7b43ace54 100644 --- a/packages/core/src/logs/types.ts +++ b/packages/logs/src/types.ts @@ -4,13 +4,18 @@ * Copyright 2016-Present Datadog, Inc. */ -import type { ErrorSource } from '../rum/types'; -import type { UserInfo } from '../sdk/UserInfoSingleton/types'; +import type { ErrorSource, UserInfo } from '@datadog/mobile-react-native'; /** * The entry point to use Datadog's Logs feature. */ export type DdLogsType = { + /** + * Enables Logs + * @param configuration: Logs configuration + */ + enable(configuration: object): Promise; + /** * Send a log with debug level. * @param message: The message to send. diff --git a/packages/logs/tsconfig.json b/packages/logs/tsconfig.json new file mode 100644 index 000000000..3214e0e7d --- /dev/null +++ b/packages/logs/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "../../tsconfig", +} diff --git a/yarn.lock b/yarn.lock index 0d50362b4..d2760bacc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2407,6 +2407,20 @@ __metadata: languageName: unknown linkType: soft +"@datadog/mobile-react-native-logs@workspace:packages/logs": + version: 0.0.0-use.local + resolution: "@datadog/mobile-react-native-logs@workspace:packages/logs" + dependencies: + "@datadog/mobile-react-native": "workspace:packages/core" + "@testing-library/react-native": 7.0.2 + react-native-builder-bob: 0.26.0 + peerDependencies: + "@datadog/mobile-react-native": "workspace:packages/core" + react: ">=16.13.1" + react-native: ">=0.63.4 <1.0" + languageName: unknown + linkType: soft + "@datadog/mobile-react-native-navigation@workspace:packages/react-native-navigation": version: 0.0.0-use.local resolution: "@datadog/mobile-react-native-navigation@workspace:packages/react-native-navigation" @@ -6056,6 +6070,7 @@ __metadata: "@babel/preset-env": ^7.25.3 "@babel/runtime": ^7.25.0 "@datadog/mobile-react-native": "workspace:packages/core" + "@datadog/mobile-react-native-logs": "workspace:packages/logs" "@react-native-community/cli": 15.0.1 "@react-native-community/cli-platform-android": 15.0.1 "@react-native-community/cli-platform-ios": 15.0.1 @@ -7929,6 +7944,7 @@ __metadata: "@babel/runtime": ^7.25.0 "@datadog/datadog-ci": ^2.39.0 "@datadog/mobile-react-native": "workspace:packages/core" + "@datadog/mobile-react-native-logs": "workspace:packages/logs" "@datadog/mobile-react-native-navigation": "workspace:packages/react-native-navigation" "@datadog/mobile-react-native-session-replay": "workspace:packages/react-native-session-replay" "@datadog/mobile-react-native-webview": "workspace:packages/react-native-webview"