Skip to content

Commit d5f5c0e

Browse files
committed
Update log levels. Clarify network errors.
1 parent 5c6d170 commit d5f5c0e

15 files changed

+145
-124
lines changed

Sources/BranchSDK/BNCEncodingUtils.m

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,22 @@ + (NSString *)stringByPercentEncodingStringForQuery:(NSString *)string {
318318
return [string stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
319319
}
320320

321+
+ (NSString *)prettyPrintJSON:(NSDictionary *)json {
322+
if (![NSJSONSerialization isValidJSONObject:json]) {
323+
[[BranchLogger shared] logWarning:@"Dictionary is not a valid JSON" error:nil];
324+
return nil;
325+
}
326+
327+
NSError *error;
328+
NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingSortedKeys | NSJSONWritingPrettyPrinted error:&error];
329+
330+
if (!data || error) {
331+
[[BranchLogger shared] logWarning:@"Failed to pretty print JSON" error:error];
332+
return nil;
333+
}
334+
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
335+
}
336+
321337
#pragma mark - Param Decoding Methods
322338

323339
+ (NSDictionary *)decodeJsonDataToDictionary:(NSData *)jsonData {

Sources/BranchSDK/BNCNetworkService.m

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ - (void) cancel {
5252
[self.sessionTask cancel];
5353
}
5454

55-
- (NSString*) stringFromResponseData {
55+
// only used in logging? Consider removing
56+
- (NSString *)stringFromResponseData {
5657
NSString *string = nil;
5758
if ([self.responseData isKindOfClass:[NSData class]]) {
5859
string = [[NSString alloc] initWithData:(NSData*)self.responseData encoding:NSUTF8StringEncoding];
@@ -148,12 +149,12 @@ - (BOOL) operationsAreSuspended {
148149

149150
#pragma mark - Operations
150151

151-
- (BNCNetworkOperation*) networkOperationWithURLRequest:(NSMutableURLRequest*)request
152+
- (BNCNetworkOperation *) networkOperationWithURLRequest:(NSMutableURLRequest*)request
152153
completion:(void (^)(id<BNCNetworkOperationProtocol>operation))completion {
153154

154155
BNCNetworkOperation *operation = [BNCNetworkOperation new];
155156
if (![request isKindOfClass:[NSMutableURLRequest class]]) {
156-
[[BranchLogger shared] logError:@"A `NSMutableURLRequest` request parameter was expected." error:nil];
157+
[[BranchLogger shared] logError:[NSString stringWithFormat:@"Expected NSMutableURLRequest, got %@", [request class]] error:nil];
157158
return nil;
158159
}
159160
operation.request = request;
@@ -162,50 +163,37 @@ - (BNCNetworkOperation*) networkOperationWithURLRequest:(NSMutableURLRequest*)re
162163
return operation;
163164
}
164165

165-
- (void) startOperation:(BNCNetworkOperation*)operation {
166+
- (void)startOperation:(BNCNetworkOperation *)operation {
166167
operation.networkService = self;
167168
if (!operation.startDate) {
168169
operation.startDate = [NSDate date];
169170
}
170171

171172
if (!operation.timeoutDate) {
172173
NSTimeInterval timeoutInterval = operation.request.timeoutInterval;
173-
if (timeoutInterval < 0.0)
174+
if (timeoutInterval < 0.0) {
174175
timeoutInterval = self.defaultTimeoutInterval;
175-
operation.timeoutDate =
176-
[[operation startDate] dateByAddingTimeInterval:timeoutInterval];
176+
}
177+
operation.timeoutDate = [[operation startDate] dateByAddingTimeInterval:timeoutInterval];
177178
}
178179

179180
if ([operation.request isKindOfClass:[NSMutableURLRequest class]]) {
180181
((NSMutableURLRequest*)operation.request).timeoutInterval =
181182
[operation.timeoutDate timeIntervalSinceDate:[NSDate date]];
182183
} else {
183-
[[BranchLogger shared] logError:@"SDK logic error. Expected mutable request in `start` method." error:nil];
184+
[[BranchLogger shared] logError:[NSString stringWithFormat:@"Expected NSMutableURLRequest, got %@", [operation.request class]] error:nil];
184185
}
185186

186-
operation.sessionTask =
187-
[self.session dataTaskWithRequest:operation.request
188-
completionHandler:
189-
^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
187+
operation.sessionTask = [self.session dataTaskWithRequest:operation.request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
190188
operation.responseData = data;
191189
operation.response = (NSHTTPURLResponse*) response;
192190
operation.error = error;
193191

194-
if (operation.response.statusCode != 404) {
195-
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Network finish operation %@ %1.3fs. Status %ld error %@.\n%@.",
196-
operation.request.URL.absoluteString,
197-
[[NSDate date] timeIntervalSinceDate:operation.startDate],
198-
(long)operation.response.statusCode,
199-
operation.error,
200-
operation.stringFromResponseData] error:nil];
201-
}
202192
if (operation.completionBlock) {
203193
operation.completionBlock(operation);
204194
}
205195
}];
206196

207-
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Network start operation %@.", operation.request.URL] error:nil];
208-
209197
[operation.sessionTask resume];
210198
}
211199

Sources/BranchSDK/BNCPreferenceHelper.m

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,9 +1083,10 @@ + (NSURL* _Nonnull) URLForPrefsFile {
10831083
attributes:nil
10841084
error:&error];
10851085
if (success) {
1086+
[[BranchLogger shared] logVerbose:[NSString stringWithFormat:@"Using storage URL %@", branchURL] error:error];
10861087
return branchURL;
10871088
} else {
1088-
[[BranchLogger shared] logError:[NSString stringWithFormat:@"CreateBranchURL failed: %@ URL: %@.", error, branchURL] error:error];
1089+
[[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Failed to create URL %@", branchURL] error:error];
10891090
}
10901091
}
10911092
return nil;
@@ -1123,8 +1124,11 @@ + (NSURL* _Nonnull) URLForPrefsFile {
11231124
withIntermediateDirectories:YES
11241125
attributes:nil
11251126
error:&error];
1126-
if (!success) {
1127-
[[BranchLogger shared] logError:[NSString stringWithFormat:@"Worst case CreateBranchURL error was: %@ URL: %@.", error, branchURL] error:error];
1127+
if (success) {
1128+
[[BranchLogger shared] logVerbose:[NSString stringWithFormat:@"Using storage URL %@", branchURL] error:error];
1129+
} else {
1130+
[[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Failed to create URL %@", branchURL] error:error];
1131+
[[BranchLogger shared] logError:@"Failed all attempts to create URLs to BNCPreferenceHelper storage." error:nil];
11281132
}
11291133
return branchURL;
11301134
}

Sources/BranchSDK/BNCServerInterface.m

Lines changed: 44 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,13 @@
99
#import "BNCServerInterface.h"
1010
#import "BNCConfig.h"
1111
#import "BNCEncodingUtils.h"
12-
#import "NSError+Branch.h"
1312
#import "BranchConstants.h"
1413
#import "NSMutableDictionary+Branch.h"
1514
#import "BranchLogger.h"
1615
#import "Branch.h"
1716
#import "BNCSKAdNetwork.h"
1817
#import "BNCReferringURLUtility.h"
19-
#import "BranchLogger.h"
18+
#import "NSError+Branch.h"
2019

2120
@interface BNCServerInterface ()
2221
@property (copy, nonatomic) NSString *requestEndpoint;
@@ -90,17 +89,13 @@ - (void)genericHTTPRequest:(NSURLRequest *)request callback:(BNCServerCallback)c
9089
}
9190

9291
- (void)genericHTTPRequest:(NSURLRequest *)request retryNumber:(NSInteger)retryNumber callback:(BNCServerCallback)callback retryHandler:(NSURLRequest *(^)(NSInteger))retryHandler {
93-
92+
9493
void (^completionHandler)(id<BNCNetworkOperationProtocol>operation) =
9594
^void (id<BNCNetworkOperationProtocol>operation) {
9695

97-
BNCServerResponse *serverResponse =
98-
[self processServerResponse:operation.response data:operation.responseData error:operation.error];
96+
BNCServerResponse *serverResponse = [self processServerResponse:operation.response data:operation.responseData error:operation.error];
9997
[self collectInstrumentationMetricsWithOperation:operation];
10098

101-
NSError *underlyingError = operation.error;
102-
NSInteger status = [serverResponse.statusCode integerValue];
103-
10499
// If the phone is in a poor network condition,
105100
// iOS will return statuses such as -1001, -1003, -1200, -9806
106101
// indicating various parts of the HTTP post failed.
@@ -109,81 +104,56 @@ - (void)genericHTTPRequest:(NSURLRequest *)request retryNumber:(NSInteger)retryN
109104
// Status 53 means the request was killed by the OS because we're still in the background.
110105
// This started happening in iOS 12 / Xcode 10 production when we're called from continueUserActivity:
111106
// but we're not fully out of the background yet.
107+
108+
NSInteger status = [serverResponse.statusCode integerValue];
109+
NSError *underlyingError = operation.error;
112110

111+
// Retry request if appropriate
113112
BOOL isRetryableStatusCode = status >= 500 || status < 0 || status == 53;
114-
115-
// Retry the request if appropriate
116113
if (retryNumber < self.preferenceHelper.retryCount && isRetryableStatusCode) {
117-
dispatch_time_t dispatchTime =
118-
dispatch_time(DISPATCH_TIME_NOW, self.preferenceHelper.retryInterval * NSEC_PER_SEC);
114+
dispatch_time_t dispatchTime = dispatch_time(DISPATCH_TIME_NOW, self.preferenceHelper.retryInterval * NSEC_PER_SEC);
119115
dispatch_after(dispatchTime, dispatch_get_main_queue(), ^{
120116
if (retryHandler) {
121-
[[BranchLogger shared] logDebug: [NSString stringWithFormat:@"Retrying request with url %@", request.URL.relativePath] error:nil];
122-
// Create the next request
117+
[[BranchLogger shared] logDebug: [NSString stringWithFormat:@"Retrying request with HTTP status code %ld", (long)status] error:underlyingError];
123118
NSURLRequest *retryRequest = retryHandler(retryNumber);
124-
[self genericHTTPRequest:retryRequest
125-
retryNumber:(retryNumber + 1)
126-
callback:callback retryHandler:retryHandler];
119+
[self genericHTTPRequest:retryRequest retryNumber:(retryNumber + 1) callback:callback retryHandler:retryHandler];
127120
}
128121
});
129122

130-
// Do not continue on if retrying, else the callback will be called incorrectly
131-
return;
132-
}
133-
134-
NSError *branchError = nil;
135-
136-
// Wrap up bad statuses w/ specific error messages
137-
if (status >= 500) {
138-
branchError = [NSError branchErrorWithCode:BNCServerProblemError error:underlyingError];
139-
}
140-
else if (status == 409) {
141-
branchError = [NSError branchErrorWithCode:BNCDuplicateResourceError error:underlyingError];
142-
}
143-
else if (status >= 400) {
144-
NSString *errorString = [serverResponse.data objectForKey:@"error"];
145-
if (![errorString isKindOfClass:[NSString class]])
146-
errorString = nil;
147-
if (!errorString)
148-
errorString = underlyingError.localizedDescription;
149-
if (!errorString)
150-
errorString = @"The request was invalid.";
151-
branchError = [NSError branchErrorWithCode:BNCBadRequestError localizedMessage:errorString];
152-
}
153-
else if (underlyingError) {
154-
branchError = [NSError branchErrorWithCode:BNCServerProblemError error:underlyingError];
155-
}
156-
157-
if (branchError) {
158-
[[BranchLogger shared] logError:[NSString stringWithFormat:@"An error prevented request to %@ from completing: %@", request.URL.absoluteString, branchError] error:branchError];
123+
} else {
124+
if (status != 200) {
125+
[[BranchLogger shared] logDebug: [NSString stringWithFormat:@"Giving up on request with HTTP status code %ld", (long)status] error:underlyingError];
126+
}
127+
128+
// Don't call on the main queue since it might be blocked.
129+
if (callback) {
130+
callback(serverResponse, underlyingError);
131+
}
159132
}
160-
161-
// Don't call on the main queue since it might be blocked.
162-
if (callback)
163-
callback(serverResponse, branchError);
164133
};
165134

135+
// Drops non-linking requests when tracking is disabled
166136
if (Branch.trackingDisabled) {
167137
NSString *endpoint = request.URL.absoluteString;
168-
169-
// if endpoint is not linking related, fail it.
138+
170139
if (![self isLinkingRelatedRequest:endpoint]) {
171140
[[BNCPreferenceHelper sharedInstance] clearTrackingInformation];
172141
NSError *error = [NSError branchErrorWithCode:BNCTrackingDisabledError];
173-
[[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Dropping Request %@: - %@", endpoint, error] error:nil];
142+
[[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Dropping non-linking request"] error:error];
174143
if (callback) {
175144
callback(nil, error);
176145
}
177146
return;
178147
}
179148
}
180149

181-
id<BNCNetworkOperationProtocol> operation =
182-
[self.networkService networkOperationWithURLRequest:request.copy completion:completionHandler];
150+
id<BNCNetworkOperationProtocol> operation = [self.networkService networkOperationWithURLRequest:request.copy completion:completionHandler];
183151
[operation start];
152+
153+
// In the past we allowed clients to provide their own networking classes.
184154
NSError *error = [self verifyNetworkOperation:operation];
185155
if (error) {
186-
[[BranchLogger shared] logError:[NSString stringWithFormat:@"Network service error: %@.", error] error:error];
156+
[[BranchLogger shared] logError:@"NetworkService returned an operation that failed validation" error:error];
187157
if (callback) {
188158
callback(nil, error);
189159
}
@@ -214,7 +184,6 @@ - (BOOL)isLinkingRelatedRequest:(NSString *)endpoint {
214184
}
215185

216186
- (NSError *)verifyNetworkOperation:(id<BNCNetworkOperationProtocol>)operation {
217-
218187
if (!operation) {
219188
NSString *message = @"A network operation instance is expected to be returned by the"
220189
" networkOperationWithURLRequest:completion: method.";
@@ -278,27 +247,23 @@ - (NSURLRequest *)prepareGetRequest:(NSDictionary *)params url:(NSString *)url k
278247

279248
NSDictionary *tmp = [self addRetryCount:retryNumber toJSON:params];
280249
NSString *requestUrlString = [NSString stringWithFormat:@"%@%@", url, [BNCEncodingUtils encodeDictionaryToQueryString:tmp]];
281-
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"URL: %@", requestUrlString] error:nil];
282250
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestUrlString]
283251
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
284252
timeoutInterval:self.preferenceHelper.timeout];
285253
[request setHTTPMethod:@"GET"];
286254
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
287255

256+
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"%@\nHeaders %@", request, [request allHTTPHeaderFields]] error:nil];
257+
288258
return request;
289259
}
290260

291261
- (NSURLRequest *)preparePostRequest:(NSDictionary *)params url:(NSString *)url key:(NSString *)key retryNumber:(NSInteger)retryNumber {
292262

293-
NSDictionary *tmp = [self addRetryCount:retryNumber toJSON:params];
263+
NSDictionary *updatedParams = [self addRetryCount:retryNumber toJSON:params];
294264

295-
NSData *postData = [BNCEncodingUtils encodeDictionaryToJsonData:tmp];
265+
NSData *postData = [BNCEncodingUtils encodeDictionaryToJsonData:updatedParams];
296266
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
297-
298-
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"URL: %@.\n", url] error:nil];
299-
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Body: %@\nJSON: %@.",
300-
params,
301-
[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]] error:nil];
302267

303268
NSMutableURLRequest *request =
304269
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
@@ -309,6 +274,10 @@ - (NSURLRequest *)preparePostRequest:(NSDictionary *)params url:(NSString *)url
309274
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
310275
[request setHTTPBody:postData];
311276

277+
if ([[BranchLogger shared] shouldLog:BranchLogLevelDebug]) {
278+
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"%@\nHeaders %@\nBody %@", request, [request allHTTPHeaderFields], [BNCEncodingUtils prettyPrintJSON:updatedParams]] error:nil];
279+
}
280+
312281
return request;
313282
}
314283

@@ -321,15 +290,21 @@ - (BNCServerResponse *)processServerResponse:(NSURLResponse *)response data:(NSD
321290
serverResponse.statusCode = @([httpResponse statusCode]);
322291
serverResponse.data = [BNCEncodingUtils decodeJsonDataToDictionary:data];
323292
serverResponse.requestId = requestId;
324-
}
325-
else {
293+
294+
if ([[BranchLogger shared] shouldLog:BranchLogLevelDebug]) {
295+
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"%@\nBody %@", response, [BNCEncodingUtils prettyPrintJSON:serverResponse.data]] error:nil];
296+
}
297+
298+
} else {
326299
serverResponse.statusCode = @(error.code);
327300
serverResponse.data = error.userInfo;
328301
serverResponse.requestId = requestId;
302+
303+
if ([[BranchLogger shared] shouldLog:BranchLogLevelDebug]) {
304+
[[BranchLogger shared] logDebug:@"Request failed with NSError" error:error];
305+
}
329306
}
330307

331-
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Server returned: %@.", serverResponse] error:nil];
332-
333308
return serverResponse;
334309
}
335310

Sources/BranchSDK/BNCServerRequestQueue.m

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,7 @@ + (instancetype)getInstance {
373373
dispatch_once(&onceToken, ^ {
374374
sharedQueue = [[BNCServerRequestQueue alloc] init];
375375
[sharedQueue retrieve];
376-
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Retrieved from storage: %@.", sharedQueue] error:nil];
376+
[[BranchLogger shared] logVerbose:[NSString stringWithFormat:@"Retrieved from storage: %@.", sharedQueue] error:nil];
377377
});
378378
return sharedQueue;
379379
}

Sources/BranchSDK/BNCSystemObserver.m

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ + (NSString *)advertiserIdentifier {
8282
(sharedManager, advertisingIdentifierSelector);
8383
uid = [uuid UUIDString];
8484
if ([uid isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
85-
[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"IDFA is all 0's. Probably running on a simulator or an App Clip."] error:nil];
85+
[[BranchLogger shared] logVerbose:[NSString stringWithFormat:@"IDFA is all 0's. Probably running on a simulator or an App Clip."] error:nil];
8686
uid = nil;
8787
}
8888
}

Sources/BranchSDK/BNCURLFilter.m

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,19 +142,21 @@ - (nullable NSDictionary *)parseJSONFromData:(NSData *)data {
142142
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
143143

144144
if (error) {
145-
[[BranchLogger shared] logError:@"Failed to parse uri_skip_list" error:error];
145+
[[BranchLogger shared] logWarning:@"Failed to parse uri_skip_list" error:error];
146146
return nil;
147147
}
148148

149+
// Given the way this is currently designed, the server will return formats that will fail this check.
150+
// Making this a verbose log until we have a chance to refactor this design.
149151
NSArray *urls = dictionary[@"uri_skip_list"];
150152
if (![urls isKindOfClass:NSArray.class]) {
151-
[[BranchLogger shared] logError:@"Failed to parse uri_skip_list is not a NSArray" error:nil];
153+
[[BranchLogger shared] logVerbose:@"Failed to parse uri_skip_list is not a NSArray" error:nil];
152154
return nil;
153155
}
154156

155157
NSNumber *version = dictionary[@"version"];
156158
if (![version isKindOfClass:NSNumber.class]) {
157-
[[BranchLogger shared] logError:@"Failed to parse uri_skip_list, version is not a NSNumber." error:nil];
159+
[[BranchLogger shared] logWarning:@"Failed to parse uri_skip_list, version is not a NSNumber." error:nil];
158160
return nil;
159161
}
160162

0 commit comments

Comments
 (0)