From e879fbb9127a1095cc3ec42a71bb17d8ef64419e Mon Sep 17 00:00:00 2001 From: Audrius Karosevicius Date: Tue, 16 Aug 2022 20:35:20 +0300 Subject: [PATCH] Set LaunchDarklySdk tag for all Timber events (#178) --- .../sdk/android/TimberLoggingTest.java | 56 +++++++++++++++++++ .../sdk/android/ConnectivityManager.java | 6 +- .../sdk/android/DefaultEventProcessor.java | 16 +++--- .../sdk/android/DefaultUserManager.java | 20 +++---- .../sdk/android/DiagnosticEventProcessor.java | 8 +-- .../sdk/android/DiagnosticStore.java | 4 +- .../launchdarkly/sdk/android/Foreground.java | 14 ++--- .../sdk/android/HttpFeatureFlagFetcher.java | 22 ++++---- .../launchdarkly/sdk/android/LDClient.java | 36 ++++++------ .../launchdarkly/sdk/android/LDConfig.java | 15 +++-- .../launchdarkly/sdk/android/LDFutures.java | 4 +- .../com/launchdarkly/sdk/android/LDUtil.java | 2 +- .../launchdarkly/sdk/android/Migration.java | 12 ++-- .../sdk/android/PollingUpdater.java | 8 +-- .../sdk/android/SharedPrefsFlagStore.java | 2 +- .../android/SharedPrefsFlagStoreManager.java | 12 ++-- .../android/SharedPrefsSummaryEventStore.java | 2 +- .../sdk/android/StreamUpdateProcessor.java | 24 ++++---- 18 files changed, 161 insertions(+), 102 deletions(-) create mode 100644 launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/TimberLoggingTest.java diff --git a/launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/TimberLoggingTest.java b/launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/TimberLoggingTest.java new file mode 100644 index 00000000..9af875a0 --- /dev/null +++ b/launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/TimberLoggingTest.java @@ -0,0 +1,56 @@ +package com.launchdarkly.sdk.android; + +import static org.junit.Assert.assertEquals; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.ArrayList; +import java.util.List; + +import timber.log.Timber; + +@RunWith(AndroidJUnit4.class) +public class TimberLoggingTest { + + @Rule + public TimberLoggingRule timberLoggingRule = new TimberLoggingRule(); + + private TestTree testTree; + + @Before + public void setUp() throws Exception { + testTree = new TestTree(); + Timber.plant(testTree); + } + + @After + public void tearDown() throws Exception { + testTree = null; + } + + @Test + public void timberTagIsLaunchDarklySdkForAllEvents() { + LDConfig.log().d("event"); + LDConfig.log().d("event"); + + assertEquals(List.of("LaunchDarklySdk", "LaunchDarklySdk"), testTree.loggedTags); + } + + private static class TestTree extends Timber.Tree { + + final List loggedTags = new ArrayList(); + + @Override + protected void log(int priority, @Nullable String tag, @NonNull String message, @Nullable Throwable t) { + loggedTags.add(tag); + } + } +} diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ConnectivityManager.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ConnectivityManager.java index 4c48e4f0..a10ed48f 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ConnectivityManager.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ConnectivityManager.java @@ -112,7 +112,7 @@ public void onError(Throwable e) { LDClient ldClient = LDClient.getForMobileKey(environmentName); ldClient.updateListenersOnFailure(connectionInformation.getLastFailure()); } catch (LaunchDarklyException ex) { - LDConfig.LOG.e(e, "Error getting LDClient for ConnectivityManager"); + LDConfig.log().e(e, "Error getting LDClient for ConnectivityManager"); } callInitCallback(); } @@ -374,13 +374,13 @@ private synchronized void updateConnectionMode(ConnectionMode connectionMode) { try { saveConnectionInformation(); } catch (Exception ex) { - LDConfig.LOG.w(ex, "Error saving connection information"); + LDConfig.log().w(ex, "Error saving connection information"); } try { LDClient ldClient = LDClient.getForMobileKey(environmentName); ldClient.updateListenersConnectionModeChanged(connectionInformation); } catch (LaunchDarklyException e) { - LDConfig.LOG.e(e, "Error getting LDClient for ConnectivityManager"); + LDConfig.log().e(e, "Error getting LDClient for ConnectivityManager"); } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultEventProcessor.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultEventProcessor.java index 518be5aa..e557376a 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultEventProcessor.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultEventProcessor.java @@ -149,12 +149,12 @@ private void postEvents(List events) { baseHeadersForRequest.put("X-LaunchDarkly-Payload-ID", eventPayloadId); baseHeadersForRequest.putAll(baseEventHeaders); - LDConfig.LOG.d("Posting %s event(s) to %s", events.size(), url); - LDConfig.LOG.d("Events body: %s", content); + LDConfig.log().d("Posting %s event(s) to %s", events.size(), url); + LDConfig.log().d("Events body: %s", content); for (int attempt = 0; attempt < 2; attempt++) { if (attempt > 0) { - LDConfig.LOG.w("Will retry posting events after 1 second"); + LDConfig.log().w("Will retry posting events after 1 second"); try { Thread.sleep(1000); } catch (InterruptedException e) {} @@ -166,11 +166,11 @@ private void postEvents(List events) { .build(); try (Response response = client.newCall(request).execute()) { - LDConfig.LOG.d("Events Response: %s", response.code()); - LDConfig.LOG.d("Events Response Date: %s", response.header("Date")); + LDConfig.log().d("Events Response: %s", response.code()); + LDConfig.log().d("Events Response Date: %s", response.header("Date")); if (!response.isSuccessful()) { - LDConfig.LOG.w("Unexpected response status when posting events: %d", response.code()); + LDConfig.log().w("Unexpected response status when posting events: %d", response.code()); if (isHttpErrorRecoverable(response.code())) { continue; } @@ -179,7 +179,7 @@ private void postEvents(List events) { tryUpdateDate(response); break; } catch (IOException e) { - LDConfig.LOG.e(e, "Unhandled exception in LaunchDarkly client attempting to connect to URI: %s", request.url()); + LDConfig.log().e(e, "Unhandled exception in LaunchDarkly client attempting to connect to URI: %s", request.url()); } } } @@ -192,7 +192,7 @@ private void tryUpdateDate(Response response) { Date date = sdf.parse(dateString); currentTimeMs = date.getTime(); } catch (ParseException pe) { - LDConfig.LOG.e(pe, "Failed to parse date header"); + LDConfig.log().e(pe, "Failed to parse date header"); } } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultUserManager.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultUserManager.java index 3bcc5f61..9cfe56d0 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultUserManager.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultUserManager.java @@ -80,7 +80,7 @@ public static String sharedPrefs(final LDUser user) { */ void setCurrentUser(final LDUser user) { String userBase64 = base64Url(user); - LDConfig.LOG.d("Setting current user to: [%s] [%s]", userBase64, userBase64ToJson(userBase64)); + LDConfig.log().d("Setting current user to: [%s] [%s]", userBase64, userBase64ToJson(userBase64)); currentUser = user; flagStoreManager.switchToUser(DefaultUserManager.sharedPrefs(user)); } @@ -98,7 +98,7 @@ public void onSuccess(JsonObject result) { @Override public void onError(Throwable e) { if (LDUtil.isClientConnected(application, environmentName)) { - LDConfig.LOG.e(e, "Error when attempting to set user: [%s] [%s]", + LDConfig.log().e(e, "Error when attempting to set user: [%s] [%s]", base64Url(currentUser), userBase64ToJson(base64Url(currentUser))); } @@ -133,14 +133,14 @@ void unregisterAllFlagsListener(@NonNull final LDAllFlagsListener listener) { */ @SuppressWarnings("JavaDoc") private void saveFlagSettings(JsonObject flagsJson, LDUtil.ResultCallback onCompleteListener) { - LDConfig.LOG.d("saveFlagSettings for user key: %s", currentUser.getKey()); + LDConfig.log().d("saveFlagSettings for user key: %s", currentUser.getKey()); try { final List flags = GsonCache.getGson().fromJson(flagsJson, FlagsResponse.class).getFlags(); flagStoreManager.getCurrentUserStore().clearAndApplyFlagUpdates(flags); onCompleteListener.onSuccess(null); } catch (Exception e) { - LDConfig.LOG.d("Invalid JsonObject for flagSettings: %s", flagsJson); + LDConfig.log().d("Invalid JsonObject for flagSettings: %s", flagsJson); onCompleteListener.onError(new LDFailure("Invalid Json received from flags endpoint", e, LDFailure.FailureType.INVALID_RESPONSE_BODY)); } } @@ -157,13 +157,13 @@ public void deleteCurrentUserFlag(@NonNull final String json, final LDUtil.Resul flagStoreManager.getCurrentUserStore().applyFlagUpdate(deleteFlagResponse); onCompleteListener.onSuccess(null); } else { - LDConfig.LOG.d("Invalid DELETE payload: %s", json); + LDConfig.log().d("Invalid DELETE payload: %s", json); onCompleteListener.onError(new LDFailure("Invalid DELETE payload", LDFailure.FailureType.INVALID_RESPONSE_BODY)); } }); } catch (Exception ex) { - LDConfig.LOG.d(ex, "Invalid DELETE payload: %s", json); + LDConfig.log().d(ex, "Invalid DELETE payload: %s", json); onCompleteListener.onError(new LDFailure("Invalid DELETE payload", ex, LDFailure.FailureType.INVALID_RESPONSE_BODY)); } @@ -173,12 +173,12 @@ public void putCurrentUserFlags(final String json, final LDUtil.ResultCallback flags = GsonCache.getGson().fromJson(json, FlagsResponse.class).getFlags(); executor.submit(() -> { - LDConfig.LOG.d("PUT for user key: %s", currentUser.getKey()); + LDConfig.log().d("PUT for user key: %s", currentUser.getKey()); flagStoreManager.getCurrentUserStore().clearAndApplyFlagUpdates(flags); onCompleteListener.onSuccess(null); }); } catch (Exception ex) { - LDConfig.LOG.d(ex, "Invalid PUT payload: %s", json); + LDConfig.log().d(ex, "Invalid PUT payload: %s", json); onCompleteListener.onError(new LDFailure("Invalid PUT payload", ex, LDFailure.FailureType.INVALID_RESPONSE_BODY)); } @@ -192,13 +192,13 @@ public void patchCurrentUserFlags(@NonNull final String json, final LDUtil.Resul flagStoreManager.getCurrentUserStore().applyFlagUpdate(flag); onCompleteListener.onSuccess(null); } else { - LDConfig.LOG.d("Invalid PATCH payload: %s", json); + LDConfig.log().d("Invalid PATCH payload: %s", json); onCompleteListener.onError(new LDFailure("Invalid PATCH payload", LDFailure.FailureType.INVALID_RESPONSE_BODY)); } }); } catch (Exception ex) { - LDConfig.LOG.d(ex, "Invalid PATCH payload: %s", json); + LDConfig.log().d(ex, "Invalid PATCH payload: %s", json); onCompleteListener.onError(new LDFailure("Invalid PATCH payload", ex, LDFailure.FailureType.INVALID_RESPONSE_BODY)); } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticEventProcessor.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticEventProcessor.java index ccaac0b4..8c585cb1 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticEventProcessor.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticEventProcessor.java @@ -126,13 +126,13 @@ void sendDiagnosticEventSync(DiagnosticEvent diagnosticEvent) { .headers(config.headersForEnvironment(environment, baseDiagnosticHeaders)) .post(RequestBody.create(content, JSON)).build(); - LDConfig.LOG.d("Posting diagnostic event to %s with body %s", request.url(), content); + LDConfig.log().d("Posting diagnostic event to %s with body %s", request.url(), content); try (Response response = client.newCall(request).execute()) { - LDConfig.LOG.d("Diagnostic Event Response: %s", response.code()); - LDConfig.LOG.d("Diagnostic Event Response Date: %s", response.header("Date")); + LDConfig.log().d("Diagnostic Event Response: %s", response.code()); + LDConfig.log().d("Diagnostic Event Response Date: %s", response.header("Date")); } catch (IOException e) { - LDConfig.LOG.w(e, "Unhandled exception in LaunchDarkly client attempting to connect to URI: %s", request.url()); + LDConfig.log().w(e, "Unhandled exception in LaunchDarkly client attempting to connect to URI: %s", request.url()); } } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticStore.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticStore.java index 8d232d84..438e7049 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticStore.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticStore.java @@ -81,7 +81,7 @@ private List getStreamInits() { DiagnosticEvent.StreamInit[] streamInitsArr = GsonCache.getGson().fromJson(streamInitsString, DiagnosticEvent.StreamInit[].class); streamInits = Arrays.asList(streamInitsArr); } catch (Exception ex) { - LDConfig.LOG.w(ex, "Invalid stream inits array in diagnostic data store"); + LDConfig.log().w(ex, "Invalid stream inits array in diagnostic data store"); streamInits = null; } return streamInits; @@ -161,4 +161,4 @@ void recordEventsInLastBatch(long eventsInLastBatch) { .putLong(EVENT_BATCH_KEY, eventsInLastBatch) .apply(); } -} \ No newline at end of file +} diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Foreground.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Foreground.java index d83620b6..2e37d392 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Foreground.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Foreground.java @@ -148,17 +148,17 @@ public void onActivityResumed(Activity activity) { if (wasBackground) { handler.post(() -> { - LDConfig.LOG.d("went foreground"); + LDConfig.log().d("went foreground"); for (Listener l : listeners) { try { l.onBecameForeground(); } catch (Exception exc) { - LDConfig.LOG.e(exc, "Listener threw exception!"); + LDConfig.log().e(exc, "Listener threw exception!"); } } }); } else { - LDConfig.LOG.d("still foreground"); + LDConfig.log().d("still foreground"); } } @@ -174,16 +174,16 @@ public void onActivityPaused(Activity activity) { handler.postDelayed(check = () -> { if (foreground && paused) { foreground = false; - LDConfig.LOG.d("went background"); + LDConfig.log().d("went background"); for (Listener l : listeners) { try { l.onBecameBackground(); } catch (Exception exc) { - LDConfig.LOG.e(exc, "Listener threw exception!"); + LDConfig.log().e(exc, "Listener threw exception!"); } } } else { - LDConfig.LOG.d("still background"); + LDConfig.log().d("still background"); } }, CHECK_DELAY); } @@ -207,4 +207,4 @@ public void onActivitySaveInstanceState(Activity activity, Bundle outState) { @Override public void onActivityDestroyed(Activity activity) { } -} \ No newline at end of file +} diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java index 4b70265d..bfa802a1 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java @@ -45,7 +45,7 @@ private HttpFeatureFlagFetcher(Context context, LDConfig config, String environm this.context = context; File cacheDir = new File(context.getCacheDir(), "com.launchdarkly.http-cache"); - LDConfig.LOG.d("Using cache at: %s", cacheDir.getAbsolutePath()); + LDConfig.log().d("Using cache at: %s", cacheDir.getAbsolutePath()); client = new OkHttpClient.Builder() .cache(new Cache(cacheDir, MAX_CACHE_SIZE_BYTES)) @@ -62,12 +62,12 @@ public synchronized void fetch(LDUser user, final LDUtil.ResultCallback init(@NonNull Application application, // initialize the client(s) once. synchronized (initLock) { if (instances != null) { - LDConfig.LOG.w("LDClient.init() was called more than once! returning primary instance."); + LDConfig.log().w("LDClient.init() was called more than once! returning primary instance."); return new LDSuccessFuture<>(instances.get(LDConfig.primaryEnvironmentName)); } if (BuildConfig.DEBUG) { @@ -116,14 +116,14 @@ public static Future init(@NonNull Application application, if (!instanceIdSharedPrefs.contains(INSTANCE_ID_KEY)) { String uuid = UUID.randomUUID().toString(); - LDConfig.LOG.i("Did not find existing instance id. Saving a new one"); + LDConfig.log().i("Did not find existing instance id. Saving a new one"); SharedPreferences.Editor editor = instanceIdSharedPrefs.edit(); editor.putString(INSTANCE_ID_KEY, uuid); editor.apply(); } instanceId = instanceIdSharedPrefs.getString(INSTANCE_ID_KEY, instanceId); - LDConfig.LOG.i("Using instance id: %s", instanceId); + LDConfig.log().i("Using instance id: %s", instanceId); Migration.migrateWhenNeeded(application, config); @@ -183,7 +183,7 @@ static LDUser customizeUser(LDUser user) { String key = user.getKey(); if (key == null || key.equals("")) { - LDConfig.LOG.i("User was created with null/empty key. Using device-unique anonymous user key: %s", LDClient.getInstanceId()); + LDConfig.log().i("User was created with null/empty key. Using device-unique anonymous user key: %s", LDClient.getInstanceId()); builder.key(LDClient.getInstanceId()); builder.anonymous(true); } @@ -204,14 +204,14 @@ static LDUser customizeUser(LDUser user) { * @return The primary LDClient instance */ public static LDClient init(Application application, LDConfig config, LDUser user, int startWaitSeconds) { - LDConfig.LOG.i("Initializing Client and waiting up to %s for initialization to complete", startWaitSeconds); + LDConfig.log().i("Initializing Client and waiting up to %s for initialization to complete", startWaitSeconds); Future initFuture = init(application, config, user); try { return initFuture.get(startWaitSeconds, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException e) { - LDConfig.LOG.e(e, "Exception during Client initialization"); + LDConfig.log().e(e, "Exception during Client initialization"); } catch (TimeoutException e) { - LDConfig.LOG.w("Client did not successfully initialize within %s seconds. It could be taking longer than expected to start up", startWaitSeconds); + LDConfig.log().w("Client did not successfully initialize within %s seconds. It could be taking longer than expected to start up", startWaitSeconds); } return instances.get(LDConfig.primaryEnvironmentName); } @@ -222,7 +222,7 @@ public static LDClient init(Application application, LDConfig config, LDUser use */ public static LDClient get() throws LaunchDarklyException { if (instances == null) { - LDConfig.LOG.e("LDClient.get() was called before init()!"); + LDConfig.log().e("LDClient.get() was called before init()!"); throw new LaunchDarklyException("LDClient.get() was called before init()!"); } return instances.get(LDConfig.primaryEnvironmentName); @@ -236,7 +236,7 @@ public static LDClient get() throws LaunchDarklyException { @SuppressWarnings("WeakerAccess") public static LDClient getForMobileKey(String keyName) throws LaunchDarklyException { if (instances == null) { - LDConfig.LOG.e("LDClient.getForMobileKey() was called before init()!"); + LDConfig.log().e("LDClient.getForMobileKey() was called before init()!"); throw new LaunchDarklyException("LDClient.getForMobileKey() was called before init()!"); } if (!(instances.containsKey(keyName))) { @@ -252,7 +252,7 @@ protected LDClient(final Application application, @NonNull final LDConfig config @VisibleForTesting protected LDClient(final Application application, @NonNull final LDConfig config, final String environmentName) { - LDConfig.LOG.i("Creating LaunchDarkly client. Version: %s", BuildConfig.VERSION_NAME); + LDConfig.log().i("Creating LaunchDarkly client. Version: %s", BuildConfig.VERSION_NAME); this.config = config; this.application = application; String sdkKey = config.getMobileKeys().get(environmentName); @@ -310,7 +310,7 @@ public Future identify(LDUser user) { return new LDFailedFuture<>(new LaunchDarklyException("User cannot be null")); } if (user.getKey() == null) { - LDConfig.LOG.w("identify called with null user or null user key!"); + LDConfig.log().w("identify called with null user or null user key!"); } return LDClient.identifyInstances(customizeUser(user)); } @@ -422,17 +422,17 @@ private EvaluationDetail variationDetailInternal(@NonNull String key, @ LDValue value = defaultValue; if (flag == null) { - LDConfig.LOG.i("Unknown feature flag \"%s\"; returning default value", key); + LDConfig.log().i("Unknown feature flag \"%s\"; returning default value", key); result = EvaluationDetail.fromValue(defaultValue, EvaluationDetail.NO_VARIATION, EvaluationReason.error(EvaluationReason.ErrorKind.FLAG_NOT_FOUND)); } else { value = flag.getValue(); if (value.isNull()) { - LDConfig.LOG.w("Feature flag \"%s\" retrieved with no value; returning default value", key); + LDConfig.log().w("Feature flag \"%s\" retrieved with no value; returning default value", key); value = defaultValue; int variation = flag.getVariation() == null ? EvaluationDetail.NO_VARIATION : flag.getVariation(); result = EvaluationDetail.fromValue(defaultValue, variation, flag.getReason()); } else if (checkType && !defaultValue.isNull() && value.getType() != defaultValue.getType()) { - LDConfig.LOG.w("Feature flag \"%s\" with type %s retrieved as %s; returning default value", key, value.getType(), defaultValue.getType()); + LDConfig.log().w("Feature flag \"%s\" with type %s retrieved as %s; returning default value", key, value.getType(), defaultValue.getType()); value = defaultValue; result = EvaluationDetail.fromValue(defaultValue, EvaluationDetail.NO_VARIATION, EvaluationReason.error(EvaluationReason.ErrorKind.WRONG_TYPE)); } else { @@ -441,7 +441,7 @@ private EvaluationDetail variationDetailInternal(@NonNull String key, @ sendFlagRequestEvent(key, flag, value, defaultValue, flag.isTrackReason() | needsReason ? result.getReason() : null); } - LDConfig.LOG.d("returning variation: %s flagKey: %s user key: %s", result, key, userManager.getCurrentUser().getKey()); + LDConfig.log().d("returning variation: %s flagKey: %s user key: %s", result, key, userManager.getCurrentUser().getKey()); updateSummaryEvents(key, flag, value, defaultValue); return result; } @@ -660,7 +660,7 @@ private void sendEvent(Event event) { if (!connectivityManager.isOffline()) { boolean processed = eventProcessor.sendEvent(event); if (!processed) { - LDConfig.LOG.w("Exceeded event queue capacity. Increase capacity to avoid dropping events."); + LDConfig.log().w("Exceeded event queue capacity. Increase capacity to avoid dropping events."); if (diagnosticStore != null) { diagnosticStore.incrementDroppedEventCount(); } @@ -687,7 +687,7 @@ private void updateSummaryEvents(String flagKey, Flag flag, LDValue result, LDVa static void triggerPollInstances() { if (instances == null) { - LDConfig.LOG.w("Cannot perform poll when LDClient has not been initialized!"); + LDConfig.log().w("Cannot perform poll when LDClient has not been initialized!"); return; } for (LDClient instance : instances.values()) { @@ -697,7 +697,7 @@ static void triggerPollInstances() { static void onNetworkConnectivityChangeInstances(boolean network) { if (instances == null) { - LDConfig.LOG.e("Tried to update LDClients with network connectivity status, but LDClient has not yet been initialized."); + LDConfig.log().e("Tried to update LDClients with network connectivity status, but LDClient has not yet been initialized."); return; } for (LDClient instance : instances.values()) { diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDConfig.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDConfig.java index bb53e867..aece004f 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDConfig.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDConfig.java @@ -28,7 +28,6 @@ public class LDConfig { static final String TIMBER_TAG = "LaunchDarklySdk"; - static final Tree LOG = Timber.tag(TIMBER_TAG); static final String SHARED_PREFS_BASE_KEY = "LaunchDarkly-"; static final String USER_AGENT_HEADER_VALUE = "AndroidClient/" + BuildConfig.VERSION_NAME; static final String AUTH_SCHEME = "api_key "; @@ -691,24 +690,24 @@ public LDConfig.Builder headerTransform(LDHeaderUpdater headerTransform) { public LDConfig build() { if (!stream) { if (pollingIntervalMillis < MIN_POLLING_INTERVAL_MILLIS) { - LDConfig.LOG.w("setPollingIntervalMillis: %s was set below the allowed minimum of: %s. Ignoring and using minimum value.", pollingIntervalMillis, MIN_POLLING_INTERVAL_MILLIS); + LDConfig.log().w("setPollingIntervalMillis: %s was set below the allowed minimum of: %s. Ignoring and using minimum value.", pollingIntervalMillis, MIN_POLLING_INTERVAL_MILLIS); pollingIntervalMillis = MIN_POLLING_INTERVAL_MILLIS; } if (!disableBackgroundUpdating && backgroundPollingIntervalMillis < pollingIntervalMillis) { - LDConfig.LOG.w("BackgroundPollingIntervalMillis: %s was set below the foreground polling interval: %s. Ignoring and using minimum value for background polling.", backgroundPollingIntervalMillis, pollingIntervalMillis); + LDConfig.log().w("BackgroundPollingIntervalMillis: %s was set below the foreground polling interval: %s. Ignoring and using minimum value for background polling.", backgroundPollingIntervalMillis, pollingIntervalMillis); backgroundPollingIntervalMillis = MIN_BACKGROUND_POLLING_INTERVAL_MILLIS; } if (eventsFlushIntervalMillis == 0) { eventsFlushIntervalMillis = pollingIntervalMillis; - LDConfig.LOG.d("Streaming is disabled, so we're setting the events flush interval to the polling interval value: %s", pollingIntervalMillis); + LDConfig.log().d("Streaming is disabled, so we're setting the events flush interval to the polling interval value: %s", pollingIntervalMillis); } } if (!disableBackgroundUpdating) { if (backgroundPollingIntervalMillis < MIN_BACKGROUND_POLLING_INTERVAL_MILLIS) { - LDConfig.LOG.w("BackgroundPollingIntervalMillis: %s was set below the minimum allowed: %s. Ignoring and using minimum value.", backgroundPollingIntervalMillis, MIN_BACKGROUND_POLLING_INTERVAL_MILLIS); + LDConfig.log().w("BackgroundPollingIntervalMillis: %s was set below the minimum allowed: %s. Ignoring and using minimum value.", backgroundPollingIntervalMillis, MIN_BACKGROUND_POLLING_INTERVAL_MILLIS); backgroundPollingIntervalMillis = MIN_BACKGROUND_POLLING_INTERVAL_MILLIS; } } @@ -718,7 +717,7 @@ public LDConfig build() { } if (diagnosticRecordingIntervalMillis < MIN_DIAGNOSTIC_RECORDING_INTERVAL_MILLIS) { - LDConfig.LOG.w("diagnosticRecordingIntervalMillis was set to %s, lower than the minimum allowed (%s). Ignoring and using minimum value.", diagnosticRecordingIntervalMillis, MIN_DIAGNOSTIC_RECORDING_INTERVAL_MILLIS); + LDConfig.log().w("diagnosticRecordingIntervalMillis was set to %s, lower than the minimum allowed (%s). Ignoring and using minimum value.", diagnosticRecordingIntervalMillis, MIN_DIAGNOSTIC_RECORDING_INTERVAL_MILLIS); diagnosticRecordingIntervalMillis = MIN_DIAGNOSTIC_RECORDING_INTERVAL_MILLIS; } @@ -758,4 +757,8 @@ public LDConfig build() { autoAliasingOptOut); } } + + public static final Tree log() { + return Timber.tag(TIMBER_TAG); + } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDFutures.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDFutures.java index 36c3ca36..bfa134fb 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDFutures.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDFutures.java @@ -90,7 +90,7 @@ synchronized void set(T result) { notifier.notifyAll(); } } else { - LDConfig.LOG.w("LDAwaitFuture set twice"); + LDConfig.log().w("LDAwaitFuture set twice"); } } @@ -102,7 +102,7 @@ synchronized void setException(@NonNull Throwable error) { notifier.notifyAll(); } } else { - LDConfig.LOG.w("LDAwaitFuture set twice"); + LDConfig.log().w("LDAwaitFuture set twice"); } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDUtil.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDUtil.java index 780e14a1..5741715d 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDUtil.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDUtil.java @@ -75,7 +75,7 @@ static boolean isClientConnected(Context context, String environmentName) { try { return deviceConnected && !LDClient.getForMobileKey(environmentName).isOffline(); } catch (LaunchDarklyException e) { - LDConfig.LOG.e(e, "Exception caught when getting LDClient"); + LDConfig.log().e(e, "Exception caught when getting LDClient"); return false; } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Migration.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Migration.java index 957e8e7d..8bfae268 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Migration.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Migration.java @@ -29,7 +29,7 @@ static void migrateWhenNeeded(Application application, LDConfig config) { try { migrate_2_7_fresh(application, config); } catch (Exception ex) { - LDConfig.LOG.w(ex, "Exception while performing fresh v2.7.0 store migration"); + LDConfig.log().w(ex, "Exception while performing fresh v2.7.0 store migration"); } } @@ -37,7 +37,7 @@ static void migrateWhenNeeded(Application application, LDConfig config) { try { migrate_2_7_from_2_6(application); } catch (Exception ex) { - LDConfig.LOG.w(ex, "Exception while performing v2.6.0 to v2.7.0 store migration"); + LDConfig.log().w(ex, "Exception while performing v2.6.0 to v2.7.0 store migration"); } } } @@ -62,7 +62,7 @@ private static String reconstructFlag(String key, String metadata, Object value) } private static void migrate_2_7_fresh(Application application, LDConfig config) { - LDConfig.LOG.d("Migrating to v2.7.0 shared preferences store"); + LDConfig.log().d("Migrating to v2.7.0 shared preferences store"); ArrayList userKeys = getUserKeysPre_2_6(application, config); SharedPreferences versionSharedPrefs = application.getSharedPreferences(LDConfig.SHARED_PREFS_BASE_KEY + "version", Context.MODE_PRIVATE); @@ -92,7 +92,7 @@ private static void migrate_2_7_fresh(Application application, LDConfig config) } if (allSuccess) { - LDConfig.LOG.d("Migration to v2.7.0 shared preferences store successful"); + LDConfig.log().d("Migration to v2.7.0 shared preferences store successful"); SharedPreferences migrations = application.getSharedPreferences(LDConfig.SHARED_PREFS_BASE_KEY + "migrations", Context.MODE_PRIVATE); boolean logged = migrations.edit().putString("v2.7.0", "v2.7.0").commit(); if (logged) { @@ -108,7 +108,7 @@ private static void migrate_2_7_fresh(Application application, LDConfig config) } private static void migrate_2_7_from_2_6(Application application) { - LDConfig.LOG.d("Migrating to v2.7.0 shared preferences store from v2.6.0"); + LDConfig.log().d("Migrating to v2.7.0 shared preferences store from v2.6.0"); Map> keyUsers = getUserKeys_2_6(application); @@ -133,7 +133,7 @@ private static void migrate_2_7_from_2_6(Application application) { } if (allSuccess) { - LDConfig.LOG.d("Migration to v2.7.0 shared preferences store successful"); + LDConfig.log().d("Migration to v2.7.0 shared preferences store successful"); SharedPreferences migrations = application.getSharedPreferences(LDConfig.SHARED_PREFS_BASE_KEY + "migrations", Context.MODE_PRIVATE); boolean logged = migrations.edit().putString("v2.7.0", "v2.7.0").commit(); if (logged) { diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/PollingUpdater.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/PollingUpdater.java index 7be3ae23..53e14be0 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/PollingUpdater.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/PollingUpdater.java @@ -27,13 +27,13 @@ public void onReceive(Context context, Intent intent) { } synchronized static void startBackgroundPolling(Context context) { - LDConfig.LOG.d("Starting background polling"); + LDConfig.log().d("Starting background polling"); startPolling(context, backgroundPollingIntervalMillis, backgroundPollingIntervalMillis); } synchronized static void startPolling(Context context, int initialDelayMillis, int intervalMillis) { stop(context); - LDConfig.LOG.d("startPolling with initialDelayMillis: %d and intervalMillis: %d", initialDelayMillis, intervalMillis); + LDConfig.log().d("startPolling with initialDelayMillis: %d and intervalMillis: %d", initialDelayMillis, intervalMillis); PendingIntent pendingIntent = getPendingIntent(context); AlarmManager alarmMgr = getAlarmManager(context); @@ -44,12 +44,12 @@ synchronized static void startPolling(Context context, int initialDelayMillis, i intervalMillis, pendingIntent); } catch (Exception ex) { - LDConfig.LOG.w(ex, "Exception occurred when creating [background] polling alarm, likely due to the host application having too many existing alarms."); + LDConfig.log().w(ex, "Exception occurred when creating [background] polling alarm, likely due to the host application having too many existing alarms."); } } synchronized static void stop(Context context) { - LDConfig.LOG.d("Stopping pollingUpdater"); + LDConfig.log().d("Stopping pollingUpdater"); PendingIntent pendingIntent = getPendingIntent(context); AlarmManager alarmMgr = getAlarmManager(context); diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsFlagStore.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsFlagStore.java index cf69f10a..2238aca4 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsFlagStore.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsFlagStore.java @@ -44,7 +44,7 @@ public void delete() { sharedPreferences = null; File file = new File(application.getFilesDir().getParent() + "/shared_prefs/" + prefsKey + ".xml"); - LDConfig.LOG.i("Deleting SharedPrefs file:%s", file.getAbsolutePath()); + LDConfig.log().i("Deleting SharedPrefs file:%s", file.getAbsolutePath()); //noinspection ResultOfMethodCallIgnored file.delete(); diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsFlagStoreManager.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsFlagStoreManager.java index c0455c85..36abab33 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsFlagStoreManager.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsFlagStoreManager.java @@ -73,7 +73,7 @@ public void switchToUser(String userKey) { // Remove oldest users until we are at MAX_USERS. for (int i = 0; i < usersToRemove; i++) { String removed = oldestFirstUsers.next(); - LDConfig.LOG.d("Exceeded max # of users: [%s] Removing user: [%s]", maxCachedUsers, removed); + LDConfig.log().d("Exceeded max # of users: [%s] Removing user: [%s]", maxCachedUsers, removed); // Load FlagStore for oldest user and delete it. flagStoreFactory.createFlagStore(storeIdentifierForUser(removed)).delete(); // Remove entry from usersSharedPrefs. @@ -99,9 +99,9 @@ public void registerListener(String key, FeatureFlagChangeListener listener) { Set oldSet = listeners.putIfAbsent(key, newSet); if (oldSet != null) { oldSet.add(listener); - LDConfig.LOG.d("Added listener. Total count: [%s]", oldSet.size()); + LDConfig.log().d("Added listener. Total count: [%s]", oldSet.size()); } else { - LDConfig.LOG.d("Added listener. Total count: 1"); + LDConfig.log().d("Added listener. Total count: 1"); } } @@ -111,7 +111,7 @@ public void unRegisterListener(String key, FeatureFlagChangeListener listener) { if (keySet != null) { boolean removed = keySet.remove(listener); if (removed) { - LDConfig.LOG.d("Removing listener for key: [%s]", key); + LDConfig.log().d("Removing listener for key: [%s]", key); } } } @@ -135,9 +135,9 @@ private Collection getCachedUsers(String activeUser) { for (String k : all.keySet()) { try { sortedMap.put((Long) all.get(k), k); - LDConfig.LOG.d("Found user: %s", userAndTimeStampToHumanReadableString(k, (Long) all.get(k))); + LDConfig.log().d("Found user: %s", userAndTimeStampToHumanReadableString(k, (Long) all.get(k))); } catch (ClassCastException cce) { - LDConfig.LOG.e(cce, "Unexpected type! This is not good"); + LDConfig.log().e(cce, "Unexpected type! This is not good"); } } return sortedMap.values(); diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsSummaryEventStore.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsSummaryEventStore.java index 97dd5824..a248bf3f 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsSummaryEventStore.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/SharedPrefsSummaryEventStore.java @@ -49,7 +49,7 @@ public synchronized void addOrUpdateEvent(String flagResponseKey, LDValue value, } editor.apply(); - LDConfig.LOG.d("Updated summary for flagKey %s to %s", flagResponseKey, GsonCache.getGson().toJson(storedCounters)); + LDConfig.log().d("Updated summary for flagKey %s to %s", flagResponseKey, GsonCache.getGson().toJson(storedCounters)); } @Override diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StreamUpdateProcessor.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StreamUpdateProcessor.java index 3ff054d6..db6f7199 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StreamUpdateProcessor.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StreamUpdateProcessor.java @@ -54,12 +54,12 @@ class StreamUpdateProcessor { synchronized void start() { if (!running && !connection401Error) { - LDConfig.LOG.d("Starting."); + LDConfig.log().d("Starting."); EventHandler handler = new EventHandler() { @Override public void onOpen() { - LDConfig.LOG.i("Started LaunchDarkly EventStream"); + LDConfig.log().i("Started LaunchDarkly EventStream"); if (diagnosticStore != null) { diagnosticStore.addStreamInit(eventSourceStarted, (int) (System.currentTimeMillis() - eventSourceStarted), false); } @@ -67,13 +67,13 @@ public void onOpen() { @Override public void onClosed() { - LDConfig.LOG.i("Closed LaunchDarkly EventStream"); + LDConfig.log().i("Closed LaunchDarkly EventStream"); } @Override public void onMessage(final String name, MessageEvent event) { final String eventData = event.getData(); - LDConfig.LOG.d("onMessage: %s: %s", name, eventData); + LDConfig.log().d("onMessage: %s: %s", name, eventData); handle(name, eventData, notifier); } @@ -84,14 +84,14 @@ public void onComment(String comment) { @Override public void onError(Throwable t) { - LDConfig.LOG.e(t, "Encountered EventStream error connecting to URI: %s", getUri(userManager.getCurrentUser())); + LDConfig.log().e(t, "Encountered EventStream error connecting to URI: %s", getUri(userManager.getCurrentUser())); if (t instanceof UnsuccessfulResponseException) { if (diagnosticStore != null) { diagnosticStore.addStreamInit(eventSourceStarted, (int) (System.currentTimeMillis() - eventSourceStarted), true); } int code = ((UnsuccessfulResponseException) t).getCode(); if (code >= 400 && code < 500) { - LDConfig.LOG.e("Encountered non-retriable error: %s. Aborting connection to stream. Verify correct Mobile Key and Stream URI", code); + LDConfig.log().e("Encountered non-retriable error: %s. Aborting connection to stream. Verify correct Mobile Key and Stream URI", code); running = false; notifier.onError(new LDInvalidResponseCodeFailure("Unexpected Response Code From Stream Connection", t, code, false)); if (code == 401) { @@ -99,7 +99,7 @@ public void onError(Throwable t) { try { LDClient.getForMobileKey(environmentName).setOffline(); } catch (LaunchDarklyException e) { - LDConfig.LOG.e(e, "Client unavailable to be set offline"); + LDConfig.log().e(e, "Client unavailable to be set offline"); } } stop(null); @@ -146,7 +146,7 @@ public void onError(Throwable t) { @NonNull private RequestBody getRequestBody(@Nullable LDUser user) { - LDConfig.LOG.d("Attempting to report user in stream"); + LDConfig.log().d("Attempting to report user in stream"); return RequestBody.create(GSON.toJson(user), JSON); } @@ -179,13 +179,13 @@ private void handle(final String name, final String eventData, }); break; default: - LDConfig.LOG.d("Found an unknown stream protocol: %s", name); + LDConfig.log().d("Found an unknown stream protocol: %s", name); onCompleteListener.onError(new LDFailure("Unknown Stream Element Type", null, LDFailure.FailureType.UNEXPECTED_STREAM_ELEMENT_TYPE)); } } void stop(final LDUtil.ResultCallback onCompleteListener) { - LDConfig.LOG.d("Stopping."); + LDConfig.log().d("Stopping."); // We do this in a separate thread because closing the stream involves a network // operation and we don't want to do a network operation on the main thread. executor.execute(() -> { @@ -202,6 +202,6 @@ private synchronized void stopSync() { } running = false; es = null; - LDConfig.LOG.d("Stopped."); + LDConfig.log().d("Stopped."); } -} \ No newline at end of file +}