Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SDK-2163] Added new BranchLogger class #1346

Merged
merged 12 commits into from
Feb 15, 2024
110 changes: 110 additions & 0 deletions Branch-TestBed/Branch-SDK-Tests/BranchLoggerTests.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
//
// BranchLoggerTests.m
// Branch-SDK-Tests
//
// Created by Nipun Singh on 2/5/24.
// Copyright © 2024 Branch, Inc. All rights reserved.
//

#import <XCTest/XCTest.h>
#import "BranchLogger.h"
#import "Branch.h"

@interface BranchLoggerTests : XCTestCase
@end

@implementation BranchLoggerTests

- (void)setUp {
nsingh-branch marked this conversation as resolved.
Show resolved Hide resolved
[super setUp];
[BranchLogger shared].loggingEnabled = NO;
[BranchLogger shared].logCallback = nil;
}

- (void)tearDown {
[BranchLogger shared].loggingEnabled = NO;
[BranchLogger shared].logCallback = nil;
[super tearDown];
}

- (void)testEnableLoggingSetsCorrectDefaultLevel {
[[Branch getInstance] enableLogging];
XCTAssertEqual([BranchLogger shared].logLevelThreshold, BranchLogLevelDebug, "Default log level should be Debug.");
}

- (void)testLogLevelThresholdBlocksLowerLevels {
[[Branch getInstance] enableLoggingAtLevel:BranchLogLevelDebug];
XCTestExpectation *expectation = [self expectationWithDescription:@"Log callback expectation for message that should pass the threshold"];

[BranchLogger shared].logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) {
if ([message isEqualToString:@"[BranchSDK][Debug][BranchLoggerTests testLogLevelThresholdBlocksLowerLevels] This message should trigger the log callback."] && logLevel >= BranchLogLevelDebug) {
[expectation fulfill];
}
};

[[BranchLogger shared] logVerbose:@"This verbose message should not trigger the log callback."];
[[BranchLogger shared] logDebug:@"This message should trigger the log callback."];

[self waitForExpectationsWithTimeout:1 handler:nil];
}

- (void)testLogCallbackExecutesWithCorrectParameters {
XCTestExpectation *expectation = [self expectationWithDescription:@"Log callback expectation"];
NSString *expectedMessage = @"[BranchSDK][Info][BranchLoggerTests testLogCallbackExecutesWithCorrectParameters] Test message";
BranchLogLevel expectedLevel = BranchLogLevelInfo;

[BranchLogger shared].logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) {
XCTAssertEqualObjects(message, expectedMessage, "Logged message does not match expected message.");
XCTAssertEqual(logLevel, expectedLevel, "Logged level does not match expected level.");
XCTAssertNil(error, "Error should be nil.");
[expectation fulfill];
};

[[Branch getInstance] enableLoggingAtLevel:BranchLogLevelInfo];
[[BranchLogger shared] logInfo:@"Test message"];

[self waitForExpectationsWithTimeout:1 handler:nil];
}

- (void)testLogLevelSpecificityFiltersLowerLevels {
[[Branch getInstance] enableLoggingAtLevel:BranchLogLevelWarning];

XCTestExpectation *verboseExpectation = [self expectationWithDescription:@"Verbose log callback"];
verboseExpectation.inverted = YES;
XCTestExpectation *errorExpectation = [self expectationWithDescription:@"Error log callback"];

__block NSUInteger callbackCount = 0;
[BranchLogger shared].logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) {
if (logLevel == BranchLogLevelVerbose) {
[verboseExpectation fulfill];
} else if (logLevel == BranchLogLevelError) {
[errorExpectation fulfill];
}
callbackCount++;
};

[[BranchLogger shared] logVerbose:@"This should not be logged due to log level threshold."];
[[BranchLogger shared] logError:@"This should be logged" error:nil];

[self waitForExpectations:@[verboseExpectation, errorExpectation] timeout:2];
XCTAssertEqual(callbackCount, 1, "Only one log callback should have been invoked.");
}

- (void)testErrorLoggingIncludesErrorDetails {
[[Branch getInstance] enableLogging];
XCTestExpectation *expectation = [self expectationWithDescription:@"Error log includes error details"];

NSError *testError = [NSError errorWithDomain:@"TestDomain" code:42 userInfo:@{NSLocalizedDescriptionKey: @"Test error description"}];
[BranchLogger shared].logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) {
if ([message containsString:@"Test error description"] && error == testError) {
[expectation fulfill];
}
};

[[BranchLogger shared] logError:@"Testing error logging" error:testError];

[self waitForExpectationsWithTimeout:1 handler:nil];
}


@end
12 changes: 12 additions & 0 deletions Branch-TestBed/Branch-TestBed.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@
C1614D56285BC8A00098946B /* LinkPresentation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1614D55285BC8A00098946B /* LinkPresentation.framework */; settings = {ATTRIBUTES = (Weak, ); }; };
C1614D5C285BD4AF0098946B /* BranchPluginSupport.h in Headers */ = {isa = PBXBuildFile; fileRef = C1614D5A285BD4AF0098946B /* BranchPluginSupport.h */; };
C1614D5D285BD4AF0098946B /* BranchPluginSupport.m in Sources */ = {isa = PBXBuildFile; fileRef = C1614D5B285BD4AF0098946B /* BranchPluginSupport.m */; };
C16B975B2B6C21C900FB0631 /* BranchLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = C16B975A2B6C21C900FB0631 /* BranchLogger.h */; };
C16B975D2B6C21DC00FB0631 /* BranchLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = C16B975C2B6C21DC00FB0631 /* BranchLogger.m */; };
C16B975F2B716C4700FB0631 /* BranchLoggerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = C16B975E2B716C4700FB0631 /* BranchLoggerTests.m */; };
C17394602A8AEE0E006068F2 /* BNCProductCategory.m in Sources */ = {isa = PBXBuildFile; fileRef = C173945F2A8AEE0E006068F2 /* BNCProductCategory.m */; };
C17394612A8C20FD006068F2 /* BNCProductCategory.h in Headers */ = {isa = PBXBuildFile; fileRef = C173945E2A8AEDFB006068F2 /* BNCProductCategory.h */; settings = {ATTRIBUTES = (Public, ); }; };
C17394642A8C228D006068F2 /* BNCCurrency.m in Sources */ = {isa = PBXBuildFile; fileRef = C17394632A8C228D006068F2 /* BNCCurrency.m */; };
Expand Down Expand Up @@ -541,6 +544,9 @@
C1614D55285BC8A00098946B /* LinkPresentation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = LinkPresentation.framework; path = System/Library/Frameworks/LinkPresentation.framework; sourceTree = SDKROOT; };
C1614D5A285BD4AF0098946B /* BranchPluginSupport.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BranchPluginSupport.h; sourceTree = "<group>"; };
C1614D5B285BD4AF0098946B /* BranchPluginSupport.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BranchPluginSupport.m; sourceTree = "<group>"; };
C16B975A2B6C21C900FB0631 /* BranchLogger.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = BranchLogger.h; sourceTree = "<group>"; };
C16B975C2B6C21DC00FB0631 /* BranchLogger.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BranchLogger.m; sourceTree = "<group>"; };
C16B975E2B716C4700FB0631 /* BranchLoggerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BranchLoggerTests.m; sourceTree = "<group>"; };
C173945E2A8AEDFB006068F2 /* BNCProductCategory.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = BNCProductCategory.h; sourceTree = "<group>"; };
C173945F2A8AEE0E006068F2 /* BNCProductCategory.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BNCProductCategory.m; sourceTree = "<group>"; };
C17394622A8C2282006068F2 /* BNCCurrency.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = BNCCurrency.h; sourceTree = "<group>"; };
Expand Down Expand Up @@ -685,6 +691,7 @@
C15CC9DF2ABCF8C8003CC339 /* BranchActivityItemTests.m */,
C17DAF7A2AC20C2000B16B1A /* BranchClassTests.m */,
C15CC9DD2ABCB549003CC339 /* BNCCurrencyTests.m */,
C16B975E2B716C4700FB0631 /* BranchLoggerTests.m */,
);
path = "Branch-SDK-Tests";
sourceTree = "<group>";
Expand Down Expand Up @@ -861,6 +868,8 @@
7E30BCF31A71EEEE00AC7402 /* BNCLinkData.m */,
4DA577151E67B1D600A43BDD /* BNCLog.h */,
4DA577161E67B1D600A43BDD /* BNCLog.m */,
C16B975A2B6C21C900FB0631 /* BranchLogger.h */,
C16B975C2B6C21DC00FB0631 /* BranchLogger.m */,
5F92B23D238486E200CA909B /* BNCNetworkInterface.h */,
5F92B23E238486E200CA909B /* BNCNetworkInterface.m */,
5F38020224DCC2E600E6FAFD /* BNCNetworkService.h */,
Expand Down Expand Up @@ -1030,6 +1039,7 @@
5F38022524DCC2E800E6FAFD /* BranchLATDRequest.h in Headers */,
4DCAC8051F426F7C00405D1D /* BNCDeviceInfo.h in Headers */,
4DCAC8061F426F7C00405D1D /* BNCEncodingUtils.h in Headers */,
C16B975B2B6C21C900FB0631 /* BranchLogger.h in Headers */,
5F92B23123834AFD00CA909B /* BNCReachability.h in Headers */,
4DCAC80E1F426F7C00405D1D /* BNCSystemObserver.h in Headers */,
C10C61AD28248E5A00761D7E /* BNCQRCodeCache.h in Headers */,
Expand Down Expand Up @@ -1344,6 +1354,7 @@
466B586A1B17779C00A69EDE /* BNCLinkCache.m in Sources */,
4D7881F7209CF28F002B750F /* BNCThreads.m in Sources */,
5F892EBE2361157E0023AEC1 /* NSError+Branch.m in Sources */,
C16B975D2B6C21DC00FB0631 /* BranchLogger.m in Sources */,
9A2B7DD61FEC3BAF00CD188B /* Branch+Validator.m in Sources */,
5FE693F82405E91500E3AEE2 /* BNCCallbackMap.m in Sources */,
5F92B240238486E200CA909B /* BNCNetworkInterface.m in Sources */,
Expand Down Expand Up @@ -1433,6 +1444,7 @@
4D1683AC2098C902008819E3 /* BranchInstallRequestTests.m in Sources */,
4D1683C72098C902008819E3 /* BNCCrashlyticsWrapperTests.m in Sources */,
5FDF91592581CDF4009BE5A3 /* BNCPartnerParametersTests.m in Sources */,
C16B975F2B716C4700FB0631 /* BranchLoggerTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
15 changes: 9 additions & 6 deletions Branch-TestBed/Branch-TestBed/AppDelegate.m
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ - (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

appDelegate = self;
BNCLogSetOutputFunction(APPLogHookFunction);
BNCLogSetDisplayLevel(BNCLogLevelAll);

/*
Set Branch.useTestBranchKey = YES; to have Branch use the test key that's in the app's
Expand All @@ -38,10 +36,15 @@ - (BOOL)application:(UIApplication *)application
// test pre init support
//[self testDispatchToIsolationQueue:branch]

// Comment out (for match guarantee testing) / or un-comment to toggle debugging:
// Note: Unit tests will fail if 'setDebug' is set.
// [branch setDebug];
[branch enableLogging];
[branch enableLoggingAtLevel:BranchLogLevelVerbose];
// [BranchLogger shared].logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) {
// // Handle the log message and error here. For example, printing to the console:
// if (error) {
// NSLog(@"[BranchLog] Level: %lu, Message: %@, Error: %@", (unsigned long)logLevel, message, error.localizedDescription);
// } else {
// NSLog(@"[BranchLog] Level: %lu, Message: %@", (unsigned long)logLevel, message);
// }
// };

// Comment out in production. Un-comment to test your Branch SDK Integration:
//[branch validateSDKIntegration];
Expand Down
5 changes: 4 additions & 1 deletion BranchSDK/BNCNetworkService.m
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#import "BNCEncodingUtils.h"
#import "BNCLog.h"
#import "NSError+Branch.h"
#import "BranchLogger.h"

#pragma mark BNCNetworkOperation

Expand Down Expand Up @@ -204,7 +205,9 @@ - (void) startOperation:(BNCNetworkOperation*)operation {
if (operation.completionBlock)
operation.completionBlock(operation);
}];
BNCLogDebug([NSString stringWithFormat:@"Network start operation %@.", operation.request.URL]);

[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Network start operation %@.", operation.request.URL]];

[operation.sessionTask resume];
}

Expand Down
4 changes: 3 additions & 1 deletion BranchSDK/BNCServerInterface.m
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#import "Branch.h"
#import "BNCSKAdNetwork.h"
#import "BNCReferringURLUtility.h"
#import "BranchLogger.h"

@interface BNCServerInterface ()
@property (copy, nonatomic) NSString *requestEndpoint;
Expand Down Expand Up @@ -329,8 +330,9 @@ - (BNCServerResponse *)processServerResponse:(NSURLResponse *)response data:(NSD
serverResponse.data = error.userInfo;
serverResponse.requestId = requestId;
}

[[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Server returned: %@.", serverResponse]];

BNCLogDebug([NSString stringWithFormat:@"Server returned: %@.", serverResponse]);
return serverResponse;
}

Expand Down
13 changes: 3 additions & 10 deletions BranchSDK/Branch.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
#import "BNCServerInterface.h"
#import "BNCServerRequestQueue.h"

#import "BranchLogger.h"
// Not used by Branch singleton public API
//#import "BranchEvent.h"
//#import "BranchScene.h"
Expand Down Expand Up @@ -564,9 +565,10 @@ extern NSString * __nonnull const BNCSpotlightFeature;
///--------------------

/**
Enable debug messages to NSLog.
Enable debug messages to os_log.
*/
- (void)enableLogging;
- (void)enableLoggingAtLevel:(BranchLogLevel)logLevel;

/**
Send requests to EU endpoints.
Expand All @@ -575,15 +577,6 @@ extern NSString * __nonnull const BNCSpotlightFeature;
*/
- (void)useEUEndpoints;

/**
setDebug is deprecated and all functionality has been disabled.

If you wish to enable logging, please invoke enableLogging.

If you wish to simulate installs, please see add a Test Device (https://help.branch.io/using-branch/docs/adding-test-devices) then reset your test device's data (https://help.branch.io/using-branch/docs/adding-test-devices#section-resetting-your-test-device-data).
*/
- (void)setDebug __attribute__((deprecated(("setDebug is replaced by enableLogging and test devices. https://help.branch.io/using-branch/docs/adding-test-devices"))));

/**
@brief Use the `validateSDKIntegration` method as a debugging aid to assure that you've
integrated the Branch SDK correctly.
Expand Down
18 changes: 8 additions & 10 deletions BranchSDK/Branch.m
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
#import "UIViewController+Branch.h"
#import "BNCReferringURLUtility.h"
#import "BNCServerAPI.h"
#import "BranchLogger.h"

#if !TARGET_OS_TV
#import "BNCUserAgentCollector.h"
Expand Down Expand Up @@ -419,20 +420,17 @@
}

- (void)enableLogging {
BNCLogSetDisplayLevel(BNCLogLevelDebug);
[self enableLoggingAtLevel:BranchLogLevelDebug];
}

- (void)useEUEndpoints {
[BNCServerAPI sharedInstance].useEUServers = YES;
- (void)enableLoggingAtLevel:(BranchLogLevel)logLevel {
BranchLogger *logger = [BranchLogger shared];
logger.loggingEnabled = YES;
logger.logLevelThreshold = logLevel;
}

- (void)setDebug {
NSLog(@"Branch setDebug is deprecated and all functionality has been disabled. "
"If you wish to enable logging, please invoke enableLogging. "
"If you wish to simulate installs, please see add a Test Device "
"(https://help.branch.io/using-branch/docs/adding-test-devices) "
"then reset your test device's data "
"(https://help.branch.io/using-branch/docs/adding-test-devices#section-resetting-your-test-device-data).");
- (void)useEUEndpoints {
[BNCServerAPI sharedInstance].useEUServers = YES;

Check warning on line 433 in BranchSDK/Branch.m

View check run for this annotation

Codecov / codecov/patch

BranchSDK/Branch.m#L433

Added line #L433 was not covered by tests
}

- (void)validateSDKIntegration {
Expand Down
39 changes: 39 additions & 0 deletions BranchSDK/BranchLogger.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//
// BranchLogger.h
// Branch
//
// Created by Nipun Singh on 2/1/24.
// Copyright © 2024 Branch, Inc. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSUInteger, BranchLogLevel) {
BranchLogLevelVerbose,
BranchLogLevelDebug,
BranchLogLevelInfo,
BranchLogLevelWarning,
BranchLogLevelError,
};

typedef void(^BranchLogCallback)(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error);
nsingh-branch marked this conversation as resolved.
Show resolved Hide resolved

NS_ASSUME_NONNULL_BEGIN

@interface BranchLogger : NSObject

@property (nonatomic, assign) BOOL loggingEnabled;
@property (nonatomic, copy, nullable) BranchLogCallback logCallback;
@property (nonatomic, assign) BranchLogLevel logLevelThreshold;

+ (instancetype _Nonnull)shared;

- (void)logError:(NSString * _Nonnull)message error:(NSError * _Nullable)error;
- (void)logWarning:(NSString * _Nonnull)message;
- (void)logInfo:(NSString * _Nonnull)message;
- (void)logDebug:(NSString * _Nonnull)message;
- (void)logVerbose:(NSString * _Nonnull)message;

@end

NS_ASSUME_NONNULL_END
Loading
Loading