From 51de9042f49fdc5c2cd56303a7deb62577b75884 Mon Sep 17 00:00:00 2001 From: LaunchDarklyReleaseBot <86431345+LaunchDarklyReleaseBot@users.noreply.github.com> Date: Tue, 23 Aug 2022 15:09:27 -0700 Subject: [PATCH] prepare 3.2.0 release (#185) * Moved primaryEnvironmentName to LDConfig, simplifying by removing primaryKey separation everywhere but the builder. Add getRequestBuilderFor a specific environment. Add static method to LDClient to get all environment names so that environments can be iterated over. Add accessor to retrieve LDClient specific UserManager. Iterate over all environments in PollingUpdater. Add environment argument to UserManager constructor, removing singleton and creating replacing init with newInstance static method. * Add back in constructor without environment to UserManager * Specialize HttpFeatureFlagFetcher to the environment, looks like UserManager may not be able to do the same so removed the environment from the constructor. * Added SharedPreferences migration strategy * All tests pass, fixed migration strategy to conform to spec, fixed primaryInstance null when offline in init, fixed primaryEnvironmentName being added to secondaryMobileKeys * Update StreamUpdateProcessor construct to take an environment for the authorization header key. * Fix issue with LDConfig mobileKeys hashmap creation. * Combine futures so LDClient init future waits on all online instances of LDClient. * Propagate IOException on closing instances to caller. * Merge futures for identify call. * Some changes from code review. * Removed static from instanceId and now old SharedPreferences will only cleared once all environments have a copy in LDClient * Fixed instanceId * Updates from PR review. * Added version and flagVersion, if available * refactor(LDClient, LDConfig): changes for PR * refactor(LDClient): changed isInternetConnected behavior for PR * refactor(LDClient): removed async getForMobileKeys and wait seconds version, replaced with method that returns requested instance * Bugfix/timber cleanup (#92) Relates to launchdarkly/android-client#60 Cleaned up timber logging messages to use string formatting rather than concatenation. Log messages should remain the same as before. Also replaced Log with Timber in the example app. * Fix crash when example app is backgrounded twice. * Add security provider update mechanism using Google Play Services to attempt a provider update when TLSv1.2 is not available. * Shared Preferences Fix for Multi Environment (#94) * fix(SharedPreferences): added more SharedPreferences first time migration and differentiated SharedPreferences by mobile key * fix(UserLocalSharePreference.java): added missing mobileKey additions to getSharedPreferences, cleaned up debugging code * Fix edge cases in how multi-environment handles connection changes. * fix(UserManagerTest.java): incorrect number of arguments to UserManager instantiation in unit test * Remove line of testing code accidentally left in and refactor shared preferences migration to make future migrations easier. * Final fixes to store migration. Should be fairly future proof. * Fix issue with primitive variation calls always returning null if fallback is null. * Remove CircleCI V1 config file. (#97) * Remove getting/comparing versions as floats (#99) To prevent floating point errors in flag version comparisons. * Include values in unknown summary events and compare values for (#100) equality when creating new summary counters. * simplify flag property deserialization * rm debugging * misc cleanup * rm debugging * add eval reason data model classes * misc fixes * serialize reason * add ability to receive evaluation reasons from LD * Changed shared preferences store system to user a single FlagStore system that holds all the information on a flag to prevent issues arising from unsynchronized separate stores for flag meta-data and values. * add methods to get value with explanation; refactor existing variation methods * Abstract FlagStoreManager from FlagStore, new FlagStoreFactory class so manager can construct FlagStores of unknown type. Reformatted interfaces. Removed unused imports. * Handle null case in allFlags, actually commit changes to UserManager. * Hopefully fix edge cases in summary event reporting to pass testing. * Hopefully fix edge cases in summary event reporting to pass testing. * Simplify getFeaturesJsonObject as no longer using -1 as placeholder for null for variations. * Make Flag non-mutable. Move GsonCache to gson package, move custom serializer/deserializers to classes in gson package and create one for PUT responses. Removed BaseUserSharedPreferences. * Send summary event even if stored flag doesn't exist. * Move sendSummaryEvent update code to UserSummaryEventSharedPreferences to synchronize to prevent data race on sending, updating, and clearing event store. Move SummaryEventSharedPreferences and UserSummaryEventSharedPreferences out of response package. * Update SharedPrefsFlagStore to hold StoreUpdatedListener in weak reference. Fix various warnings. * Migration code for upcoming flagstore. * Remove couple of debug messages. * Handle todos. * Revert to old String behavior for allFlags, initialize WeakReference in SharedPrefsFlagStore. * Better implementation of EvaluationReason serialization type adapter. * Revert "Better implementation of EvaluationReason serialization type adapter." Wrong branch... This reverts commit 69c1c9b2b8d9a3b72fcd856f2b6da0e8c896802c. * Gw/ch29266/flagstore (#105) * Changed shared preferences store system to user a single FlagStore system that holds all the information on a flag to prevent issues arising from unsynchronized separate stores for flag meta-data and values. * Abstract FlagStoreManager from FlagStore, new FlagStoreFactory class so manager can construct FlagStores of unknown type. Reformatted interfaces. Removed unused imports. * Handle null case in allFlags, actually commit changes to UserManager. * Hopefully fix edge cases in summary event reporting to pass testing. * Hopefully fix edge cases in summary event reporting to pass testing. * Simplify getFeaturesJsonObject as no longer using -1 as placeholder for null for variations. * Make Flag non-mutable. Move GsonCache to gson package, move custom serializer/deserializers to classes in gson package and create one for PUT responses. Removed BaseUserSharedPreferences. * Send summary event even if stored flag doesn't exist. * Move sendSummaryEvent update code to UserSummaryEventSharedPreferences to synchronize to prevent data race on sending, updating, and clearing event store. Move SummaryEventSharedPreferences and UserSummaryEventSharedPreferences out of response package. * Update SharedPrefsFlagStore to hold StoreUpdatedListener in weak reference. Fix various warnings. * Migration code for upcoming flagstore. * Remove couple of debug messages. * Handle todos. * Revert to old String behavior for allFlags, initialize WeakReference in SharedPrefsFlagStore. * Better implementation of EvaluationReason serialization type adapter. * Remove isUnknown argument from SummaryEventSharedPreferences methods. Use Runnable instead of Callable in UserManager to avoid useless return nulls. Rename FlagStoreFactoryInterface to FlagStoreFactory. * Statically initialize Gson instance in GsonCache. * Make Gson instance in GsonCache final on principle. * Return json flags as JsonElement in allFlags map. (#106) * Bump ok-http version to 3.9.1 (#107) * fix annotations so eval reasons are serialized in events * fix/expand doc comments for public methods * typo * typo * add version string getter method * Check for null key before file comparison check. (#110) * [ch33658] Add unsafeReset() for LDClient testing re-initialization (#111) Add `unsafeReset()` method to close and clear instances for re-initializing client between tests. Update LDClientTest to call `unsafeReset()` before tests. * [ch33846] Rename tests to not start with capitals and general refactoring (#112) * Rename tests to not start with capitals * Reindent MultiEnvironmentLDClientTest to be consistent * Optimize imports * Move TLS patch into TLSUtils * Make setModernTlsVersionsOnSocket private and remove redundant null check * Remove code duplication in LDClient track overloaded methods. * Remove validateParameter in LDClient that was using a NullPointerException as a null test. * Simplify Debounce to use listener instead of callback. * Add documentation for flagstore implementation (#113) * [ch35150] Unit tests and bug fixes (#114) - Use android test orchestrator to run tests isolated from each other. This prevents the issues testing singletons. Also enabled option to clear package data between runs allowing more extensive flagstore testing. - Remove unsafe reset as it was added only for allowing testing the LDClient singleton. - Tests for new FlagStore code. - Convenience test FlagBuilder - Fix Migration to not turn all flags into Strings - Fix issue with clearAndApplyFlagUpdates not generating correct events for listeners. * Add compatibility behavior to stringVariation and allFlags methods. (#115) If a Json flag is requested with stringVariation it will serialize it to a String. Json flags will also be serialized to Strings for the map returned by allFlags() * Update LDUser not to store all fields as Json. (#116) Add testing rule to setup and teardown Timber trees for debug logging. Add additional LDUser tests. Fixed a bit of flakiness in deletesOlderThanLastFiveStoredUsers test that showed up all of a sudden. * Add metricValue field to CustomEvent, add overloaded track method for (#118) creating custom events with metricValues. * [ch37794] Run connected emulator tests in CircleCI (#120) * [ch34533] connection status, removing guava, network restructuring. (#117) * Add ConnectionInformation class. * Remove all internal uses of Guava. * Update StreamUpdateProcessor to only debounce ping events. * Add a connection state monitor to the example app. * rename repo and package name and apply markdown templates (#121) * Fix issue that stream could be started before stopping when calling identify. (#122) * Revert "Fix issue that stream could be started before stopping when calling identify. (#122)" This reverts commit fdede38cf58af2802a116599580ea64a07d7dc4a. * Revert "rename repo and package name and apply markdown templates (#121)" This reverts commit 221527594dd632322aaf7edafa0b5edff719132e. * Revert "Revert "Fix issue that stream could be started before stopping when calling identify. (#122)"" This reverts commit 08498127157e038ec3e9d29203d29ea09c326679. * Revert "Revert "rename repo and package name and apply markdown templates (#121)"" This reverts commit bbbeb8103b58764a57fddb7bc72b93608702dbe7. * Fix thread leak on identify call from restarting EventProcessor without shutting it down first. (#123) * Add top level try/catch to migration methods. Check flag version SharedPreferences object for String type before cast. (#124) * Update Throttler to call runnable on background thread. (#125) * Fix ConcurrentModificationException of instance map (#126) Move iteration over client instances for ConnectivityReceiver and PollingUpdater to within LDClient to allow synchronizing on initialization. * adding a circleci badge to the readme (#127) * Fix bug where `stop` in StreamUpdateProcessor could not call it's listener when the stream is already closed. This caused a race condition in repeated stream restarts that could put the SDK in a bad state. * Change LDAwaitFuture to not treat zero timeout as unlimited timeout Treating a timeout of zero as unlimited caused a change in behavior when initializing the SDK. This update restores the behavior init had when zero was passed as the timeout argument from pre-2.8.0. Also improves handling of spurious wakeups, and includes test cases for LDAwaitFuture. * Revert "Merge remote-tracking branch 'remotes/origin/experiment' into next-release" This reverts commit 3ac167fb01c5d6545cf91af7817818e313108f80, reversing changes made to d26e00666a89997c4b548bc54fd82882e518b4bc. * CircleCI fixes (#131) * Better ci fix (#132) * Speedup tests by building on macOS (#137) * Background identify fixes (#133) Add new testing controllers for network and foreground states. For network control, mobile data must be disabled on recent Android versions, updated circleci config to do this. Add new connectivity manager tests. Made EventProcessor and UserManager minimal interfaces for mocking, with actual implementations moved to DefaultEventProcessor and DefaultUserManager. Fixed issue with blocking in background modes. * Experimentation 1.5 updates (#134) * add entire compile-time classpath to javadoc classpath * javadoc fixes:
is not a thing * do fail on javadoc errors * add javadoc step, misc CI cleanup * misc javadoc fixes * remove unintentional(?) immediate event flush; clean up event tests * remove unreliable test assumption about elapsed time * [ch57098] Deprecate LDCountryCode (#141) Deprecate LDCountryCode class and LDUser setters that take LDCountryCode as an argument. * Catch `SecurityException` when setting alarm in case there are already (#143) the maximum allowed number of alarms on Samsung devices. * Revert "[ch57098] Deprecate LDCountryCode (#141)" so we can do a patch release first. This reverts commit c0e71ae1214f6227f2643c467c26bdd1c07ec531. * Revert "Revert "[ch57098] Deprecate LDCountryCode (#141)" so we can do a patch release" This reverts commit 23b930ff0ff503a50af8c0ee4dcb294f688deb82. * Deprecate public classes (#145) * Deprecate some unnecessarily public classes, duplicate classes as non-public to avoid using the deprecated classes. * [ch61092] Add event payload ID. (#147) * Add event retry. (#149) * Fix javadoc comment for release. * Fix broken merge. * [ch65133] Deprecate classes (#150) * Deprecate UserSummaryEventSharedPreferences, SummaryEventSharedPreferences, FeatureFlagFetcher, Util, Debounce. * Improve Javadoc and reduce interface clutter. (#152) * Save Javadoc artifact and include logcat in circle output with tee. (#153) * Save Javadoc artifact on circleci. * Add step to kill emulator after tests, and tee output of logcat for visibility during run. * [ch62120] Background during identify callback (#154) * Adding more connectivity manager tests. * Updated internal `Foreground` class to call listeners on a background thread. * Add some comments explaining the behavior of test controllers. * Adding fixes for cases where the completion callback may not be called. * [ch65914] Diagnostic events (#156) * [ch65352] Expose LDValue rather than Gson types (#158) * Remove SET_ALARM permission. The comment that this was required for background updating is incorrect, this permission is only for sending broadcasts to an alarm clock application, something we do not do, and should never do. (#159) * Fix minimum diagnostic recording interval comment. (#160) * Data since date was not getting reset after each periodic diagnostic event. (#161) * [ch75315] Add maxCachedUsers configuration option (#162) Adds maxCachedUsers configuration option for configuring the limit on how many users have their flags cached locally. * Configure okhttp cache for polling requests to be stored in a subdirectory of the application cache directory. (#164) * Fixes ch76614 and add test of null fallback unknown flag event generation. Also some finishing touches to LDValue changes, including LDClientInterface updates, more tests, and improvements to null behavior handling. (#163) * Removing ldvalue changes before release (#165) * Revert "[ch65352] Expose LDValue rather than Gson types (#158)" This reverts commit 1e29a827 * Fixes after revert. * [ch69437] Support for setting additional headers to be included in requests. (#166) * [ch89933] Improve resiliency of store for summary events. (#167) See launchdarkly/android-client-sdk#105 for the original issue. * [ch94053] Improve throttler behavior. (#169) * Add doubleVariation, doubleVariationDetail. (#171) Deprecates floatVariation, floatVariationDetail. * Provide pollUri configuration and deprecate baseUri. (#172) * Fix throttler behavior to ensure attempt count resets are not cancelled (#178) * [ch98336] Broaden catch statement on scheduling polling alarm (#181) This is to handle more than just the SecurityException that Samsung throws, as we've gotten an issue report that some devices throw a IllegalStateException instead. * Removed the guides link * Include flag key in warning message when converting a json flag to a string (#185) * (2.x) Prevent NullPointerException when diagnostic processor shut down before starting. (#210) * Release 2.14.2 (#130) ## [2.14.2] - 2021-06-02 ### Fixed - Added check to prevent `NullPointerException` in `DiagnosticEventProcessor.stopScheduler` when `LDClient.close` is called before the application is foregrounded when the SDK was initialized in the background. ([#127](https://github.com/launchdarkly/android-client-sdk/issues/127)) - Log message warning that JSON flag was requested as a String has been updated to include the key of the flag requested to assist in discovering which flag is being requested with an unexpected type. ([#116](https://github.com/launchdarkly/android-client-sdk/issues/116)) * Bump version and update changelog for release. * Explicitly specify android:exported attribute on manifest receivers. (#211) * Update java common (#212) * Flag PendingIntent on new enough platforms as the flag is required on Android S+ (#213) * Add try for getting network capabilities (#214) * ch103537 bump java-sdk-common to 1.2 to support inExperiment on eval reason (#215) * Remove `allowBackup` manifest attribute that can conflict with the application's (#217) * Update the version to 2.8.9 * Add explicit proguard directives for keeping BroadcastReceivers. (#219) * Using the version that still support Java 8 but pin the grgit core behind the scene * Remove Android Appcompat dependency (#222) * Bump dependencies and reorganize Gradle file somewhat. (#223) * Add the null check to prevent multiple allocation of the DiagnosticEventProcessor * Fix sonatype release plugin (#226) * Add .ldrelease configuration (#227) * Add contract test service (#228) * Fix test service failing on later API versions (#229) * Add usesCleartextTraffic=true to contract-tests AndroidManifest This allows the contract tests to work on API level 28 and above * Fix start-emulator.sh to pick the newest image instead of the oldest * Refactor CI config into separate jobs with a matrix (#230) * Don't auto-retry emulator tests (#231) * Add contract tests for API level 21 (#232) * Remove unnecessary locking in LDClient (#233) * Remove `synchronized` keywords from every `LDClient` method * Treat `instances` as immutable, and swap out the whole map after constructing all the clients * Use a lock to ensure we don't try to init twice * Update `ConnectivityManager` so it now manages `DiagnosticEventManager` * Run contract tests on Android 31, 33 (#234) * Unsuppress streaming/requests and polling/requests (#236) * don't create a new executor just to trigger a flush * remove short publishing timeout, use defaults of 60 retries & 10 seconds * Serialize null values of `anonymous` as null (#237) * fix URL path concatenation to avoid double slashes * fix NPE in edge case where variation is null but value isn't * use SecureRandom instead of Random, just to make scanners happier * rm unused * fix deletion versioning logic, implement tombstones (#244) * disable contract tests for API 31/33 * use okhttp-eventsource 1.11.3 * ensure timed-out clients get closed in contract tests * clean up instances map on close (#247) * clean up instances map on close * improve atomicity of access to instances, ensure they can't be modified via closed clients * update more methods that iterate over instances * rm unnecessary LDClientControl * use com.launchdarkly.logging with Timber adapter (#235) Co-authored-by: Gavin Whelan
+ * LDConfig config = new LDConfig.Builder()
+ * .logAdapter(LDAndroidLogging.adapter())
+ * .build();
+ *
+ *
+ * By default, debug-level logging is disabled and all other levels are enabled. To change this,
+ * use {@link LDConfig.Builder#logLevel(LDLogLevel)}.
+ * @since 3.2.0
+ */
+public abstract class LDAndroidLogging {
+ public static LDLogAdapter adapter() {
+ return AdapterImpl.INSTANCE;
+ }
+
+ private static final class AdapterImpl implements LDLogAdapter {
+ static final AdapterImpl INSTANCE = new AdapterImpl();
+
+ @Override
+ public Channel newChannel(String name) {
+ return new ChannelImpl(name);
+ }
+ }
+
+ private static final class ChannelImpl extends ChannelImplBase {
+ public ChannelImpl(String tag) {
+ super(tag);
+ }
+
+ @Override
+ public boolean isEnabled(LDLogLevel level) {
+ return Log.isLoggable(tag, toAndroidLogLevel(level));
+ }
+
+ private static int toAndroidLogLevel(LDLogLevel level) {
+ switch (level) {
+ case DEBUG: return Log.DEBUG;
+ case INFO: return Log.INFO;
+ case WARN: return Log.WARN;
+ case ERROR: return Log.ERROR;
+ default: return Log.VERBOSE;
+ }
+ }
+
+ @Override
+ protected void logInternal(LDLogLevel level, String text) {
+ switch (level) {
+ case DEBUG:
+ Log.d(tag, text);
+ break;
+ case INFO:
+ Log.i(tag, text);
+ break;
+ case WARN:
+ Log.w(tag, text);
+ break;
+ case ERROR:
+ Log.e(tag, text);
+ break;
+ }
+ }
+ }
+
+ abstract static class ChannelImplBase implements LDLogAdapter.Channel {
+ protected final String tag;
+
+ public ChannelImplBase(String tag) {
+ this.tag = tag;
+ }
+
+ protected abstract void logInternal(LDLogLevel level, String text);
+
+ // To avoid unnecessary string computations for debug output, we don't want to
+ // pre-format messages for disabled levels. We'll avoid that by checking if the
+ // level is enabled first.
+
+ @Override
+ public void log(LDLogLevel level, Object message) {
+ if (isEnabled(level)) {
+ logInternal(level, message == null ? null : message.toString());
+ }
+ }
+
+ @Override
+ public void log(LDLogLevel level, String format, Object param) {
+ if (isEnabled(level)) {
+ logInternal(level, SimpleFormat.format(format, param));
+ }
+ }
+
+ @Override
+ public void log(LDLogLevel level, String format, Object param1, Object param2) {
+ if (isEnabled(level)) {
+ logInternal(level, SimpleFormat.format(format, param1, param2));
+ }
+ }
+
+ @Override
+ public void log(LDLogLevel level, String format, Object... params) {
+ if (isEnabled(level)) {
+ logInternal(level, SimpleFormat.format(format, params));
+ }
+ }
+ }
+}
diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDClient.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDClient.java
index 5ee5c5af..0430bb2b 100644
--- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDClient.java
+++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDClient.java
@@ -9,6 +9,8 @@
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogValues;
import com.launchdarkly.sdk.EvaluationDetail;
import com.launchdarkly.sdk.EvaluationReason;
import com.launchdarkly.sdk.LDUser;
@@ -36,7 +38,6 @@
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
-import timber.log.Timber;
/**
* Client for accessing LaunchDarkly's Feature Flag system. This class enforces a singleton pattern.
@@ -53,6 +54,8 @@ public class LDClient implements LDClientInterface, Closeable {
// A lock to ensure calls to `init()` are serialized.
static Object initLock = new Object();
+ private static volatile LDLogger sharedLogger;
+
private final Application application;
private final LDConfig config;
private final DefaultUserManager userManager;
@@ -64,6 +67,7 @@ public class LDClient implements LDClientInterface, Closeable {
private final List
+ * The
+ * Specifying {@code logAdapter(Logs.none())} completely disables log output.
+ *
+ * For more about logging adapters,
+ * see the SDK reference guide
+ * and the API documentation for
+ *
+ * This is only applicable when using an implementation of logging that does not have its own
+ * external filter/configuration mechanism, such as {@link LDAndroidLogging}. It adds
+ * a log level filter so that log messages at lower levels are suppressed. The default is
+ * {@link LDLogLevel#INFO}, meaning that {@code INFO}, {@code WARN}, and {@code ERROR} levels
+ * are enabled, but {@code DEBUG} is disabled. To enable {@code DEBUG} level as well:
+ *
+ * Or, to raise the logging threshold so that only WARN and ERROR levels are enabled, and
+ * DEBUG and INFO are disabled:
+ *
+ * When using {@link LDTimberLogging}, Timber has its own mechanism for determining whether
+ * to enable debug-level logging, so this method has no effect.
+ *
+ * @param logLevel the lowest level of logging to enable
+ * @return the builder
+ * @since 3.2.0
+ * @see #logAdapter(LDLogAdapter)
+ * @see #loggerName(String)
+ */
+ public LDConfig.Builder logLevel(LDLogLevel logLevel) {
+ this.logLevel = logLevel;
+ return this;
+ }
+
+ /**
+ * Specifies a custom logger name/tag for the SDK.
+ *
+ * When using Timber or native Android logging, this becomes the tag for all SDK log output.
+ * If you have specified a different logging implementation with {@link #logAdapter(LDLogAdapter)},
+ * the meaning of the logger name depends on the logging framework.
+ *
+ * If not specified, the default is "LaunchDarklySdk".
+ *
+ * @param loggerName the logger name or tag
+ * @return the builder
+ * @since 3.2.0
+ * @see #logAdapter(LDLogAdapter)
+ * @see #logLevel(LDLogLevel)
+ */
+ public LDConfig.Builder loggerName(String loggerName) {
+ this.loggerName = loggerName == null ? DEFAULT_LOGGER_NAME : loggerName;
+ return this;
+ }
+
+ private static LDLogAdapter defaultLogAdapter() {
+ return LDTimberLogging.adapter();
+ }
+
/**
* Returns the configured {@link LDConfig} object.
* @return the configuration
*/
public LDConfig build() {
+ LDLogAdapter actualLogAdapter = Logs.level(logAdapter,
+ logLevel == null ? DEFAULT_LOG_LEVEL : logLevel);
+ // Note: if the log adapter is LDTimberLogging, then Logs.level has no effect - we will still
+ // forward all of our logging to Timber, because it has its own mechanism for filtering out
+ // debug logging. But if it is LDAndroidLogging or anything else, Logs.level ensures that no
+ // output at a lower level than logLevel will be sent anywhere.
+
+ LDLogger logger = LDLogger.withAdapter(actualLogAdapter, loggerName);
+
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);
+ logger.warn(
+ "setPollingIntervalMillis: {} was set below the allowed minimum of: {}. 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);
+ logger.warn(
+ "BackgroundPollingIntervalMillis: {} was set below the foreground polling interval: {}. 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);
+ // this is a normal occurrence, so don't log a warning about it
}
}
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);
+ logger.warn(
+ "BackgroundPollingIntervalMillis: {} was set below the minimum allowed: {}. Ignoring and using minimum value.",
+ backgroundPollingIntervalMillis, MIN_BACKGROUND_POLLING_INTERVAL_MILLIS);
backgroundPollingIntervalMillis = MIN_BACKGROUND_POLLING_INTERVAL_MILLIS;
}
}
if (eventsFlushIntervalMillis == 0) {
- eventsFlushIntervalMillis = DEFAULT_FLUSH_INTERVAL_MILLIS;
+ eventsFlushIntervalMillis = DEFAULT_FLUSH_INTERVAL_MILLIS; // this is a normal occurrence, so don't log a warning about it
}
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);
+ logger.warn(
+ "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;
}
@@ -754,11 +886,9 @@ public LDConfig build() {
wrapperVersion,
maxCachedUsers,
headerTransform,
- autoAliasingOptOut);
+ autoAliasingOptOut,
+ actualLogAdapter,
+ loggerName);
}
}
-
- 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 bfa134fb..6d26dba4 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");
+ LDClient.getSharedLogger().warn("LDAwaitFuture set twice");
}
}
@@ -102,7 +102,7 @@ synchronized void setException(@NonNull Throwable error) {
notifier.notifyAll();
}
} else {
- LDConfig.log().w("LDAwaitFuture set twice");
+ LDClient.getSharedLogger().warn("LDAwaitFuture set twice");
}
}
diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDTimberLogging.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDTimberLogging.java
new file mode 100644
index 00000000..5df2fbe4
--- /dev/null
+++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDTimberLogging.java
@@ -0,0 +1,112 @@
+package com.launchdarkly.sdk.android;
+
+import com.launchdarkly.logging.LDLogAdapter;
+import com.launchdarkly.logging.LDLogLevel;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import timber.log.Timber;
+import timber.log.Timber.DebugTree;
+import timber.log.Timber.Tree;
+
+/**
+ * Allows LaunchDarkly log output to be forwarded to Timber.
+ *
+ * Currently this is the default logging implementation; in the future, we may change the default to
+ * {@link LDAndroidLogging}.
+ *
+ * When this logging implementation is active, the SDK will automatically call
+ * {@code Timber.plant(new Timber.DebugTree)} at initialization time if and only if
+ * {@code BuildConfig.DEBUG} is true. This behavior is for consistency with the default behavior of
+ * earlier SDK versions and may be removed in the future. It can be changed with
+ * {@link Adapter#autoPlantDebugTree(boolean)}.
+ *
+ * @since 3.2.0
+ */
+public abstract class LDTimberLogging {
+ public static LDLogAdapter adapter() {
+ return new Adapter(true);
+ }
+
+ /**
+ * A Timber implementation of the {@link LDLogAdapter} interface.
+ */
+ public static final class Adapter implements LDLogAdapter, LDLogAdapter.IsConfiguredExternally {
+ // Note: implementing IsConfiguredExternally tells the logging framework that it should not
+ // try to do level filtering, because Timber has its own configuration mechanisms.
+ private final boolean autoPlantDebugTree;
+
+ Adapter(boolean autoPlantDebugTree) {
+ this.autoPlantDebugTree = autoPlantDebugTree;
+ }
+
+ /**
+ * Returns a modified logging adapter with the automatic debug tree behavior changed.
+ *
+ * By default, this property is true, meaning that the SDK will automatically call
+ * {@code Timber.plant(new Timber.DebugTree)} at initialization time if and only if
+ * {@code BuildConfig.DEBUG} is true. If you set it to false as shown below, then the
+ * SDK will never create a {@code DebugTree} and the application is responsible for
+ * doing so if desired.
+ *
+ * In a future version, this automatic behavior may be removed, since it is arguably more
+ * correct for library code to leave all Tree-planting to the application. The behavior is
+ * retained in the current release for backward compatibility.
+ * com.launchdarkly.logging
+ * API defines the {@link LDLogAdapter} interface to specify where log output should be sent. By default,
+ * it is set to {@link LDTimberLogging#adapter()}, meaning that output will be sent to the
+ * Timber framework and controlled by whatever Timber
+ * configuration the application has created. You may change this to {@link LDAndroidLogging#adapter()}
+ * to bypass Timber and use Android native logging directly; or, use the
+ * {@link com.launchdarkly.logging.Logs} factory methods, or a custom implementation, to handle log
+ * output differently.
+ * com.launchdarkly.logging
.
+ *
+ * @param logAdapter an {@link LDLogAdapter} for the desired logging implementation
+ * @return the builder
+ * @since 3.2.0
+ * @see #logLevel(LDLogLevel)
+ * @see #loggerName(String)
+ * @see LDTimberLogging
+ * @see LDAndroidLogging
+ * @see com.launchdarkly.logging.Logs
+ */
+ public LDConfig.Builder logAdapter(LDLogAdapter logAdapter) {
+ this.logAdapter = logAdapter == null ? defaultLogAdapter() : logAdapter;
+ return this;
+ }
+
+ /**
+ * Specifies the lowest level of logging to enable.
+ *
+ *
+ * LDConfig config = new LDConfig.Builder()
+ * .logAdapter(LDAndroidLogging.adapter())
+ * .level(LDLogLevel.DEBUG)
+ * .build();
+ *
+ *
+ * LDConfig config = new LDConfig.Builder()
+ * .logAdapter(LDAndroidLogging.adapter())
+ * .level(LDLogLevel.WARN)
+ * .build();
+ *
+ *
+ * LDConfig config = new LDConfig.Builder()
+ * .mobileKey("mobile-key")
+ * .logAdapter(LDTimberLogging.adapter().autoPlantDebugTree(false))
+ * .build();
+ *