Skip to content

Commit e879fbb

Browse files
authored
Set LaunchDarklySdk tag for all Timber events (#178)
1 parent 5487a31 commit e879fbb

18 files changed

+161
-102
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.launchdarkly.sdk.android;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import androidx.annotation.NonNull;
6+
import androidx.annotation.Nullable;
7+
import androidx.test.ext.junit.runners.AndroidJUnit4;
8+
9+
import org.junit.After;
10+
import org.junit.Before;
11+
import org.junit.Rule;
12+
import org.junit.Test;
13+
import org.junit.runner.RunWith;
14+
15+
import java.util.ArrayList;
16+
import java.util.List;
17+
18+
import timber.log.Timber;
19+
20+
@RunWith(AndroidJUnit4.class)
21+
public class TimberLoggingTest {
22+
23+
@Rule
24+
public TimberLoggingRule timberLoggingRule = new TimberLoggingRule();
25+
26+
private TestTree testTree;
27+
28+
@Before
29+
public void setUp() throws Exception {
30+
testTree = new TestTree();
31+
Timber.plant(testTree);
32+
}
33+
34+
@After
35+
public void tearDown() throws Exception {
36+
testTree = null;
37+
}
38+
39+
@Test
40+
public void timberTagIsLaunchDarklySdkForAllEvents() {
41+
LDConfig.log().d("event");
42+
LDConfig.log().d("event");
43+
44+
assertEquals(List.of("LaunchDarklySdk", "LaunchDarklySdk"), testTree.loggedTags);
45+
}
46+
47+
private static class TestTree extends Timber.Tree {
48+
49+
final List<String> loggedTags = new ArrayList<String>();
50+
51+
@Override
52+
protected void log(int priority, @Nullable String tag, @NonNull String message, @Nullable Throwable t) {
53+
loggedTags.add(tag);
54+
}
55+
}
56+
}

launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ConnectivityManager.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ public void onError(Throwable e) {
112112
LDClient ldClient = LDClient.getForMobileKey(environmentName);
113113
ldClient.updateListenersOnFailure(connectionInformation.getLastFailure());
114114
} catch (LaunchDarklyException ex) {
115-
LDConfig.LOG.e(e, "Error getting LDClient for ConnectivityManager");
115+
LDConfig.log().e(e, "Error getting LDClient for ConnectivityManager");
116116
}
117117
callInitCallback();
118118
}
@@ -374,13 +374,13 @@ private synchronized void updateConnectionMode(ConnectionMode connectionMode) {
374374
try {
375375
saveConnectionInformation();
376376
} catch (Exception ex) {
377-
LDConfig.LOG.w(ex, "Error saving connection information");
377+
LDConfig.log().w(ex, "Error saving connection information");
378378
}
379379
try {
380380
LDClient ldClient = LDClient.getForMobileKey(environmentName);
381381
ldClient.updateListenersConnectionModeChanged(connectionInformation);
382382
} catch (LaunchDarklyException e) {
383-
LDConfig.LOG.e(e, "Error getting LDClient for ConnectivityManager");
383+
LDConfig.log().e(e, "Error getting LDClient for ConnectivityManager");
384384
}
385385
}
386386

launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultEventProcessor.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,12 @@ private void postEvents(List<Event> events) {
149149
baseHeadersForRequest.put("X-LaunchDarkly-Payload-ID", eventPayloadId);
150150
baseHeadersForRequest.putAll(baseEventHeaders);
151151

152-
LDConfig.LOG.d("Posting %s event(s) to %s", events.size(), url);
153-
LDConfig.LOG.d("Events body: %s", content);
152+
LDConfig.log().d("Posting %s event(s) to %s", events.size(), url);
153+
LDConfig.log().d("Events body: %s", content);
154154

155155
for (int attempt = 0; attempt < 2; attempt++) {
156156
if (attempt > 0) {
157-
LDConfig.LOG.w("Will retry posting events after 1 second");
157+
LDConfig.log().w("Will retry posting events after 1 second");
158158
try {
159159
Thread.sleep(1000);
160160
} catch (InterruptedException e) {}
@@ -166,11 +166,11 @@ private void postEvents(List<Event> events) {
166166
.build();
167167

168168
try (Response response = client.newCall(request).execute()) {
169-
LDConfig.LOG.d("Events Response: %s", response.code());
170-
LDConfig.LOG.d("Events Response Date: %s", response.header("Date"));
169+
LDConfig.log().d("Events Response: %s", response.code());
170+
LDConfig.log().d("Events Response Date: %s", response.header("Date"));
171171

172172
if (!response.isSuccessful()) {
173-
LDConfig.LOG.w("Unexpected response status when posting events: %d", response.code());
173+
LDConfig.log().w("Unexpected response status when posting events: %d", response.code());
174174
if (isHttpErrorRecoverable(response.code())) {
175175
continue;
176176
}
@@ -179,7 +179,7 @@ private void postEvents(List<Event> events) {
179179
tryUpdateDate(response);
180180
break;
181181
} catch (IOException e) {
182-
LDConfig.LOG.e(e, "Unhandled exception in LaunchDarkly client attempting to connect to URI: %s", request.url());
182+
LDConfig.log().e(e, "Unhandled exception in LaunchDarkly client attempting to connect to URI: %s", request.url());
183183
}
184184
}
185185
}
@@ -192,7 +192,7 @@ private void tryUpdateDate(Response response) {
192192
Date date = sdf.parse(dateString);
193193
currentTimeMs = date.getTime();
194194
} catch (ParseException pe) {
195-
LDConfig.LOG.e(pe, "Failed to parse date header");
195+
LDConfig.log().e(pe, "Failed to parse date header");
196196
}
197197
}
198198
}

launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultUserManager.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public static String sharedPrefs(final LDUser user) {
8080
*/
8181
void setCurrentUser(final LDUser user) {
8282
String userBase64 = base64Url(user);
83-
LDConfig.LOG.d("Setting current user to: [%s] [%s]", userBase64, userBase64ToJson(userBase64));
83+
LDConfig.log().d("Setting current user to: [%s] [%s]", userBase64, userBase64ToJson(userBase64));
8484
currentUser = user;
8585
flagStoreManager.switchToUser(DefaultUserManager.sharedPrefs(user));
8686
}
@@ -98,7 +98,7 @@ public void onSuccess(JsonObject result) {
9898
@Override
9999
public void onError(Throwable e) {
100100
if (LDUtil.isClientConnected(application, environmentName)) {
101-
LDConfig.LOG.e(e, "Error when attempting to set user: [%s] [%s]",
101+
LDConfig.log().e(e, "Error when attempting to set user: [%s] [%s]",
102102
base64Url(currentUser),
103103
userBase64ToJson(base64Url(currentUser)));
104104
}
@@ -133,14 +133,14 @@ void unregisterAllFlagsListener(@NonNull final LDAllFlagsListener listener) {
133133
*/
134134
@SuppressWarnings("JavaDoc")
135135
private void saveFlagSettings(JsonObject flagsJson, LDUtil.ResultCallback<Void> onCompleteListener) {
136-
LDConfig.LOG.d("saveFlagSettings for user key: %s", currentUser.getKey());
136+
LDConfig.log().d("saveFlagSettings for user key: %s", currentUser.getKey());
137137

138138
try {
139139
final List<Flag> flags = GsonCache.getGson().fromJson(flagsJson, FlagsResponse.class).getFlags();
140140
flagStoreManager.getCurrentUserStore().clearAndApplyFlagUpdates(flags);
141141
onCompleteListener.onSuccess(null);
142142
} catch (Exception e) {
143-
LDConfig.LOG.d("Invalid JsonObject for flagSettings: %s", flagsJson);
143+
LDConfig.log().d("Invalid JsonObject for flagSettings: %s", flagsJson);
144144
onCompleteListener.onError(new LDFailure("Invalid Json received from flags endpoint", e, LDFailure.FailureType.INVALID_RESPONSE_BODY));
145145
}
146146
}
@@ -157,13 +157,13 @@ public void deleteCurrentUserFlag(@NonNull final String json, final LDUtil.Resul
157157
flagStoreManager.getCurrentUserStore().applyFlagUpdate(deleteFlagResponse);
158158
onCompleteListener.onSuccess(null);
159159
} else {
160-
LDConfig.LOG.d("Invalid DELETE payload: %s", json);
160+
LDConfig.log().d("Invalid DELETE payload: %s", json);
161161
onCompleteListener.onError(new LDFailure("Invalid DELETE payload",
162162
LDFailure.FailureType.INVALID_RESPONSE_BODY));
163163
}
164164
});
165165
} catch (Exception ex) {
166-
LDConfig.LOG.d(ex, "Invalid DELETE payload: %s", json);
166+
LDConfig.log().d(ex, "Invalid DELETE payload: %s", json);
167167
onCompleteListener.onError(new LDFailure("Invalid DELETE payload", ex,
168168
LDFailure.FailureType.INVALID_RESPONSE_BODY));
169169
}
@@ -173,12 +173,12 @@ public void putCurrentUserFlags(final String json, final LDUtil.ResultCallback<V
173173
try {
174174
final List<Flag> flags = GsonCache.getGson().fromJson(json, FlagsResponse.class).getFlags();
175175
executor.submit(() -> {
176-
LDConfig.LOG.d("PUT for user key: %s", currentUser.getKey());
176+
LDConfig.log().d("PUT for user key: %s", currentUser.getKey());
177177
flagStoreManager.getCurrentUserStore().clearAndApplyFlagUpdates(flags);
178178
onCompleteListener.onSuccess(null);
179179
});
180180
} catch (Exception ex) {
181-
LDConfig.LOG.d(ex, "Invalid PUT payload: %s", json);
181+
LDConfig.log().d(ex, "Invalid PUT payload: %s", json);
182182
onCompleteListener.onError(new LDFailure("Invalid PUT payload", ex,
183183
LDFailure.FailureType.INVALID_RESPONSE_BODY));
184184
}
@@ -192,13 +192,13 @@ public void patchCurrentUserFlags(@NonNull final String json, final LDUtil.Resul
192192
flagStoreManager.getCurrentUserStore().applyFlagUpdate(flag);
193193
onCompleteListener.onSuccess(null);
194194
} else {
195-
LDConfig.LOG.d("Invalid PATCH payload: %s", json);
195+
LDConfig.log().d("Invalid PATCH payload: %s", json);
196196
onCompleteListener.onError(new LDFailure("Invalid PATCH payload",
197197
LDFailure.FailureType.INVALID_RESPONSE_BODY));
198198
}
199199
});
200200
} catch (Exception ex) {
201-
LDConfig.LOG.d(ex, "Invalid PATCH payload: %s", json);
201+
LDConfig.log().d(ex, "Invalid PATCH payload: %s", json);
202202
onCompleteListener.onError(new LDFailure("Invalid PATCH payload", ex,
203203
LDFailure.FailureType.INVALID_RESPONSE_BODY));
204204
}

launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticEventProcessor.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -126,13 +126,13 @@ void sendDiagnosticEventSync(DiagnosticEvent diagnosticEvent) {
126126
.headers(config.headersForEnvironment(environment, baseDiagnosticHeaders))
127127
.post(RequestBody.create(content, JSON)).build();
128128

129-
LDConfig.LOG.d("Posting diagnostic event to %s with body %s", request.url(), content);
129+
LDConfig.log().d("Posting diagnostic event to %s with body %s", request.url(), content);
130130

131131
try (Response response = client.newCall(request).execute()) {
132-
LDConfig.LOG.d("Diagnostic Event Response: %s", response.code());
133-
LDConfig.LOG.d("Diagnostic Event Response Date: %s", response.header("Date"));
132+
LDConfig.log().d("Diagnostic Event Response: %s", response.code());
133+
LDConfig.log().d("Diagnostic Event Response Date: %s", response.header("Date"));
134134
} catch (IOException e) {
135-
LDConfig.LOG.w(e, "Unhandled exception in LaunchDarkly client attempting to connect to URI: %s", request.url());
135+
LDConfig.log().w(e, "Unhandled exception in LaunchDarkly client attempting to connect to URI: %s", request.url());
136136
}
137137
}
138138
}

launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DiagnosticStore.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ private List<DiagnosticEvent.StreamInit> getStreamInits() {
8181
DiagnosticEvent.StreamInit[] streamInitsArr = GsonCache.getGson().fromJson(streamInitsString, DiagnosticEvent.StreamInit[].class);
8282
streamInits = Arrays.asList(streamInitsArr);
8383
} catch (Exception ex) {
84-
LDConfig.LOG.w(ex, "Invalid stream inits array in diagnostic data store");
84+
LDConfig.log().w(ex, "Invalid stream inits array in diagnostic data store");
8585
streamInits = null;
8686
}
8787
return streamInits;
@@ -161,4 +161,4 @@ void recordEventsInLastBatch(long eventsInLastBatch) {
161161
.putLong(EVENT_BATCH_KEY, eventsInLastBatch)
162162
.apply();
163163
}
164-
}
164+
}

launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/Foreground.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -148,17 +148,17 @@ public void onActivityResumed(Activity activity) {
148148

149149
if (wasBackground) {
150150
handler.post(() -> {
151-
LDConfig.LOG.d("went foreground");
151+
LDConfig.log().d("went foreground");
152152
for (Listener l : listeners) {
153153
try {
154154
l.onBecameForeground();
155155
} catch (Exception exc) {
156-
LDConfig.LOG.e(exc, "Listener threw exception!");
156+
LDConfig.log().e(exc, "Listener threw exception!");
157157
}
158158
}
159159
});
160160
} else {
161-
LDConfig.LOG.d("still foreground");
161+
LDConfig.log().d("still foreground");
162162
}
163163
}
164164

@@ -174,16 +174,16 @@ public void onActivityPaused(Activity activity) {
174174
handler.postDelayed(check = () -> {
175175
if (foreground && paused) {
176176
foreground = false;
177-
LDConfig.LOG.d("went background");
177+
LDConfig.log().d("went background");
178178
for (Listener l : listeners) {
179179
try {
180180
l.onBecameBackground();
181181
} catch (Exception exc) {
182-
LDConfig.LOG.e(exc, "Listener threw exception!");
182+
LDConfig.log().e(exc, "Listener threw exception!");
183183
}
184184
}
185185
} else {
186-
LDConfig.LOG.d("still background");
186+
LDConfig.log().d("still background");
187187
}
188188
}, CHECK_DELAY);
189189
}
@@ -207,4 +207,4 @@ public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
207207
@Override
208208
public void onActivityDestroyed(Activity activity) {
209209
}
210-
}
210+
}

launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ private HttpFeatureFlagFetcher(Context context, LDConfig config, String environm
4545
this.context = context;
4646

4747
File cacheDir = new File(context.getCacheDir(), "com.launchdarkly.http-cache");
48-
LDConfig.LOG.d("Using cache at: %s", cacheDir.getAbsolutePath());
48+
LDConfig.log().d("Using cache at: %s", cacheDir.getAbsolutePath());
4949

5050
client = new OkHttpClient.Builder()
5151
.cache(new Cache(cacheDir, MAX_CACHE_SIZE_BYTES))
@@ -62,12 +62,12 @@ public synchronized void fetch(LDUser user, final LDUtil.ResultCallback<JsonObje
6262
? getReportRequest(user)
6363
: getDefaultRequest(user);
6464

65-
LDConfig.LOG.d(request.toString());
65+
LDConfig.log().d(request.toString());
6666
Call call = client.newCall(request);
6767
call.enqueue(new Callback() {
6868
@Override
6969
public void onFailure(@NonNull Call call, @NonNull IOException e) {
70-
LDConfig.LOG.e(e, "Exception when fetching flags.");
70+
LDConfig.log().e(e, "Exception when fetching flags.");
7171
callback.onError(new LDFailure("Exception while fetching flags", e, LDFailure.FailureType.NETWORK_FAILURE));
7272
}
7373

@@ -81,20 +81,20 @@ public void onResponse(@NonNull Call call, @NonNull final Response response) {
8181
}
8282
if (!response.isSuccessful()) {
8383
if (response.code() == 400) {
84-
LDConfig.LOG.e("Received 400 response when fetching flag values. Please check recommended ProGuard settings");
84+
LDConfig.log().e("Received 400 response when fetching flag values. Please check recommended ProGuard settings");
8585
}
8686
callback.onError(new LDInvalidResponseCodeFailure("Unexpected response when retrieving Feature Flags: " + response + " using url: "
8787
+ request.url() + " with body: " + body, response.code(), true));
8888
}
89-
LDConfig.LOG.d(body);
90-
LDConfig.LOG.d("Cache hit count: %s Cache network Count: %s", client.cache().hitCount(), client.cache().networkCount());
91-
LDConfig.LOG.d("Cache response: %s", response.cacheResponse());
92-
LDConfig.LOG.d("Network response: %s", response.networkResponse());
89+
LDConfig.log().d(body);
90+
LDConfig.log().d("Cache hit count: %s Cache network Count: %s", client.cache().hitCount(), client.cache().networkCount());
91+
LDConfig.log().d("Cache response: %s", response.cacheResponse());
92+
LDConfig.log().d("Network response: %s", response.networkResponse());
9393

9494
JsonObject jsonObject = JsonParser.parseString(body).getAsJsonObject();
9595
callback.onSuccess(jsonObject);
9696
} catch (Exception e) {
97-
LDConfig.LOG.e(e, "Exception when handling response for url: %s with body: %s", request.url(), body);
97+
LDConfig.log().e(e, "Exception when handling response for url: %s with body: %s", request.url(), body);
9898
callback.onError(new LDFailure("Exception while handling flag fetch response", e, LDFailure.FailureType.INVALID_RESPONSE_BODY));
9999
} finally {
100100
if (response != null) {
@@ -111,7 +111,7 @@ private Request getDefaultRequest(LDUser user) {
111111
if (config.isEvaluationReasons()) {
112112
uri += "?withReasons=true";
113113
}
114-
LDConfig.LOG.d("Attempting to fetch Feature flags using uri: %s", uri);
114+
LDConfig.log().d("Attempting to fetch Feature flags using uri: %s", uri);
115115
return new Request.Builder().url(uri)
116116
.headers(config.headersForEnvironment(environmentName, null))
117117
.build();
@@ -122,7 +122,7 @@ private Request getReportRequest(LDUser user) {
122122
if (config.isEvaluationReasons()) {
123123
reportUri += "?withReasons=true";
124124
}
125-
LDConfig.LOG.d("Attempting to report user using uri: %s", reportUri);
125+
LDConfig.log().d("Attempting to report user using uri: %s", reportUri);
126126
String userJson = GSON.toJson(user);
127127
RequestBody reportBody = RequestBody.create(userJson, JSON);
128128

0 commit comments

Comments
 (0)