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

feat(SDK-2217): add logger with loglevel support #1005

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .mocharc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@

module.exports = {
require: ['./node_modules/google-closure-library', './test/branch-deps.js', 'global-jsdom/register', './test/test-utils.js', './node_modules/sinon/lib/sinon.js'],
spec: ['./test/0_config.js','./test/0_queue.js','./test/1_utils.js','./test/6_branch_new.js', './test/journeys_utils.js']
spec: ['./test/0_config.js','./test/0_queue.js','./test/1_utils.js','./test/6_branch_new.js', './test/journeys_utils.js', './test/8_logger.js']
};
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ src/4_banner_css.js src/4_banner_html.js\
src/5_banner.js\
src/6_branch.js\
src/7_initialization.js\
src/8_logger.js\
src/branch_view.js\
src/journeys_utils.js

Expand Down
23 changes: 16 additions & 7 deletions src/6_branch.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ goog.require('config');
goog.require('safejson');
goog.require('branch_view');
goog.require('journeys_utils');
goog.require('Logger');

/*globals Ti, BranchStorage, require */

Expand Down Expand Up @@ -133,6 +134,8 @@ Branch = function() {

this._server = new Server();

this._logger = new Logger();

var sdk = 'web';

/** @type {Array<utils.listener>} */
Expand Down Expand Up @@ -373,6 +376,7 @@ Branch.prototype['init'] = wrap(
utils.userPreferences.enableExtendedJourneysAssist = options && options['enableExtendedJourneysAssist'] ? options['enableExtendedJourneysAssist'] : utils.userPreferences.enableExtendedJourneysAssist;
utils.extendedJourneysAssistExpiryTime = options && options['extendedJourneysAssistExpiryTime'] && Number.isInteger(options['extendedJourneysAssistExpiryTime']) ? options['extendedJourneysAssistExpiryTime'] : utils.extendedJourneysAssistExpiryTime;
utils.userPreferences.allowErrorsInCallback = false;
this._logger.setLevel(options['logLevel'] || 'error');
utils.getClientHints();

if (utils.userPreferences.trackingDisabled) {
Expand Down Expand Up @@ -1008,7 +1012,7 @@ Branch.prototype['track'] = wrap(callback_params.CALLBACK_ERR, function(done, ev

}
else {
console.warn("track method currently supports only pageview event.");
this._logger.log('warn', 'track method currently supports only pageview event.');
}
});

Expand Down Expand Up @@ -1694,6 +1698,7 @@ Branch.prototype['closeJourney'] = wrap(callback_params.CALLBACK_ERR, function(d
journeys_utils.animateBannerExit(journeys_utils.banner, true);
}
else {
this._logger.log('info', 'Journey already dismissed.');
return done('Journey already dismissed.');
}
});
Expand All @@ -1702,10 +1707,10 @@ Branch.prototype['closeJourney'] = wrap(callback_params.CALLBACK_ERR, function(d

Branch.prototype['banner'] = wrap(callback_params.CALLBACK_ERR, function(done, options, data) {
var banner_deprecation_msg = 'The "banner" method is deprecated and will be removed in future versions. Please use Branch Journeys instead. For more information and migration steps, visit: https://help.branch.io/using-branch/docs/journeys-overview';
console.warn(banner_deprecation_msg);
this._logger.log('warn', banner_deprecation_msg);
var platform = utils.getPlatformByUserAgent();
if ([ "other", "desktop" ].includes(platform)) {
console.info("banner functionality is not supported on this platform");
this._logger.log('info', 'banner functionality is not supported on this platform');
}
else {
data = data || {};
Expand Down Expand Up @@ -1945,6 +1950,10 @@ Branch.prototype['setAPIResponseCallback'] = wrap(callback_params.NO_CALLBACK, f
* Gets the referring link from storage (session, local) wih link expiry applied if provided.
*/
Branch.prototype['referringLink'] = function(withExtendedJourneysAssist) {
if (!utils.isBoolean(withExtendedJourneysAssist)) {
this._logger.log('error', `referringLink: parameter withExtendedJourneysAssist must be boolean`);
return;
}
return this._referringLink(withExtendedJourneysAssist);
};

Expand All @@ -1959,7 +1968,7 @@ Branch.prototype['setDMAParamsForEEA'] = wrap(callback_params.CALLBACK_ERR, func
try {
const validateParam = (param, paramName) => {
if (!utils.isBoolean(param)) {
console.warn(`setDMAParamsForEEA: ${paramName} must be boolean, but got ${param}`);
this._logger.log('error', `setDMAParamsForEEA: ${paramName} must be boolean, but got ${param}`);
return false;
}
return true;
Expand All @@ -1980,7 +1989,7 @@ Branch.prototype['setDMAParamsForEEA'] = wrap(callback_params.CALLBACK_ERR, func

this._storage.set('branch_dma_data', safejson.stringify(dmaObj), true);
} catch (e) {
console.error("setDMAParamsForEEA::An error occurred while setting DMA parameters for EEA", e);
this._logger.log('error', 'setDMAParamsForEEA::An error occurred while setting DMA parameters for EEA', e);
}
done();
}, true);
Expand All @@ -2004,7 +2013,7 @@ Branch.prototype['setRequestMetaData'] = function(key, value) {
this.requestMetadata = utils.addPropertyIfNotNull(this.requestMetadata, key, value);
}
catch (e) {
console.error("An error occured while setting request metadata", e);
this._logger.log('error', 'An error occured while setting request metadata', e);
}
};

Expand All @@ -2015,7 +2024,7 @@ Branch.prototype['setRequestMetaData'] = function(key, value) {
*/
Branch.prototype['setAPIUrl'] = function(url) {
if (!utils.isValidURL(url)) {
console.error("setAPIUrl: Invalid URL format. Default URL will be set.");
this._logger.log('error', 'setAPIUrl: Invalid URL format. Default URL will be set.');
return;
}

Expand Down
94 changes: 94 additions & 0 deletions src/8_logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
'use strict';
goog.provide('Logger');
// jscs:disable validateIndentation
/**
* @constructor
*/

Logger = function() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is a wrapper over the native console, should we include a tag or namespace like BranchSDK, so that messages emitted from this logger are easily filterable?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

something like BranchSDK::<error message> ?

/**
* @private
* @type {string}
*/
this.level_ = 'error';
this.levelsOrdered = [ 'verbose', 'info', 'warn', 'error', 'none' ];
};

/**
* Sets the logging level.
* @param {string} level - The logging level to set.
*/
Logger.prototype.setLevel = function(level) {
if (this.levelsOrdered.indexOf(level) !== -1) {
this.level_ = level;
}
else {
console.error(`Invalid log level: ${level}`);
gdeluna-branch marked this conversation as resolved.
Show resolved Hide resolved
}
};

/**
* Logs a message to the console if the log level allows it.
* @param {string} level - The logging level of the message.
* @param {...*} args - The message to log.
*/
Logger.prototype.log = function(level) {
var args = Array.prototype.slice.call(arguments, 1);
if (this.shouldLog(level)) {
switch (level) {
case 'info':
JagadeeshKaricherla-branch marked this conversation as resolved.
Show resolved Hide resolved
this.logInfo_(args);
break;
case 'warn':
this.logWarning_(args);
break;
case 'error':
this.logError_(args);
break;
}
}
};

/**
* Checks if a message with the given level should be logged.
* @private
* @param {string} level - The logging level of the message.
* @return {boolean} True if the message should be logged, false otherwise.
*/
Logger.prototype.shouldLog = function(level) {
if (this.level_ === 'none') {
return false;
}
let currentLevelIndex = this.levelsOrdered.indexOf(this.level_);
let logLevelIndex = this.levelsOrdered.indexOf(level);
return logLevelIndex >= currentLevelIndex;
};

/**
* Logs an info message to the console.
* @private
* @param {Array} args - The message to log.
*/
Logger.prototype.logInfo_ = function(args) {
console.info.apply(console, args);
};

/**
* Logs a warning message to the console.
* @private
* @param {Array} args - The message to log.
*/
Logger.prototype.logWarning_ = function(args) {
console.warn.apply(console, args);
};

/**
* Logs an error message to the console.
* @private
* @param {Array} args - The message to log.
*/
Logger.prototype.logError_ = function(args) {
console.error.apply(console, args);
};
// jscs:enable validateIndentation

28 changes: 18 additions & 10 deletions test/6_branch_new.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ var sinon = require('sinon');
goog.require('Branch');
goog.require('utils');
goog.require('task_queue');
goog.require('Logger');

describe('Branch - new', function() {
const sandbox = sinon.createSandbox();
Expand Down Expand Up @@ -67,7 +68,8 @@ describe('Branch - new', function() {
_storage: {
set: () => {}
},
_queue: task_queue()
_queue: task_queue(),
_logger: new Logger()
};
const storageSetStub = sandbox.stub(thisObj._storage, 'set');
const dmaObj = {};
Expand All @@ -83,7 +85,8 @@ describe('Branch - new', function() {
_storage: {
set: () => {}
},
_queue: task_queue()
_queue: task_queue(),
_logger: new Logger()
};
const storageSetStub = sandbox.stub(thisObj._storage, 'set');
branch_instance.setDMAParamsForEEA.call(thisObj);
Expand All @@ -94,7 +97,8 @@ describe('Branch - new', function() {
_storage: {
set: () => {}
},
_queue: task_queue()
_queue: task_queue(),
_logger: new Logger()
};
const storageSetStub = sandbox.stub(thisObj._storage, 'set');
const dmaObj = {};
Expand All @@ -109,9 +113,10 @@ describe('Branch - new', function() {
_storage: {
set: () => {}
},
_queue: task_queue()
_queue: task_queue(),
_logger: new Logger()
};
const consoleErrorStub = sandbox.stub(console, 'warn');
const consoleErrorStub = sandbox.stub(console, 'error');
try {
const dmaObj = {};
dmaObj.eeaRegion = null;
Expand All @@ -129,9 +134,10 @@ describe('Branch - new', function() {
_storage: {
set: () => {}
},
_queue: task_queue()
_queue: task_queue(),
_logger: new Logger()
};
const consoleErrorStub = sandbox.stub(console, 'warn');
const consoleErrorStub = sandbox.stub(console, 'error');
try {
const dmaObj = {};
dmaObj.eeaRegion = true;
Expand All @@ -149,9 +155,10 @@ describe('Branch - new', function() {
_storage: {
set: () => {}
},
_queue: task_queue()
_queue: task_queue(),
_logger: new Logger()
};
const consoleErrorStub = sandbox.stub(console, 'warn');
const consoleErrorStub = sandbox.stub(console, 'error');
try {
const dmaObj = {};
dmaObj.eeaRegion = true;
Expand All @@ -169,7 +176,8 @@ describe('Branch - new', function() {
_storage: {
set: () => {}
},
_queue: task_queue()
_queue: task_queue(),
_logger: new Logger()
};
sandbox.stub(thisObj._storage, 'set').throws(new Error('Mock error'));
const consoleErrorStub = sandbox.stub(console, 'error');
Expand Down
Loading
Loading