Skip to content
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
6 changes: 3 additions & 3 deletions src/audienceManager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SDKLoggerApi } from './sdkRuntimeModels';
import Logger from './logger';
import {
FetchUploader,
XHRUploader,
Expand All @@ -21,12 +21,12 @@ export interface IAudienceMemberships {
export default class AudienceManager {
public url: string = '';
public userAudienceAPI: AsyncUploader;
public logger: SDKLoggerApi;
public logger: Logger;

constructor(
userAudienceUrl: string,
apiKey: string,
logger: SDKLoggerApi,
logger: Logger,
) {
this.logger = logger;
this.url = `https://${userAudienceUrl}${apiKey}/audience`;
Expand Down
5 changes: 3 additions & 2 deletions src/batchUploader.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Batch } from '@mparticle/event-models';
import Constants from './constants';
import { SDKEvent, SDKLoggerApi } from './sdkRuntimeModels';
import { SDKEvent } from './sdkRuntimeModels';
import { convertEvents } from './sdkToEventsApiConverter';
import { MessageType, EventType } from './types';
import { getRampNumber, isEmpty } from './utils';
Expand All @@ -14,6 +14,7 @@ import {
import { IMParticleUser } from './identity-user-interfaces';
import { IMParticleWebSDKInstance } from './mp-instance';
import { appendUserInfo } from './user-utils';
import Logger from './logger';
/**
* BatchUploader contains all the logic to store/retrieve events and batches
* to/from persistence, and upload batches to mParticle.
Expand Down Expand Up @@ -418,7 +419,7 @@ export class BatchUploader {
// TODO: Refactor to use logger as a class method
// https://go.mparticle.com/work/SQDSDKS-5167
private async uploadBatches(
logger: SDKLoggerApi,
logger: Logger,
batches: Batch[],
useBeacon: boolean
): Promise<Batch[] | null> {
Expand Down
36 changes: 24 additions & 12 deletions src/logger.js → src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
function Logger(config) {
import { SDKInitConfig } from "./sdkRuntimeModels";

interface Logger {
verbose: (msg: string) => void;
warning: (msg: string) => void;
error: (msg: string) => void;
setLogLevel: (msg: string) => void;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
setLogLevel: (msg: string) => void;
setLogLevel: (logLevel: string) => void;

Copy link
Collaborator

Choose a reason for hiding this comment

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

Also, you should create a type definition for log level. For example:

type LogLevelType = 'none' | 'verbose' | 'warning' | 'error';

logLevel: string;
logger: this;
}

function Logger(this: Logger, config: SDKInitConfig): void {
var self = this;
var logLevel = config.logLevel || 'warning';
var logLevel: string = config.logLevel || 'warning';
Copy link
Collaborator

Choose a reason for hiding this comment

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

You should use let and const in this file instead of var.

if (config.hasOwnProperty('logger')) {
this.logger = config.logger;
this.logger = config.logger as Logger;
} else {
this.logger = new ConsoleLogger();
}

this.verbose = function(msg) {
this.verbose = function(msg: string) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we try replacing this with arrow functions?

this.verbose = (msg: string) => {
    if (logLevel === 'verbose') {
        this.logger.verbose?.(msg);
    }
};

if (logLevel !== 'none') {
if (self.logger.verbose && logLevel === 'verbose') {
self.logger.verbose(msg);
}
}
};

this.warning = function(msg) {
this.warning = function(msg: string) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we trying using arrow function here too?

this.warning = (msg: string) => {
        if (logLevel !== 'none') {
            if (
                this.logger.warning &&
                (logLevel === 'verbose' || logLevel === 'warning')
            ) {
                this.logger.warning(msg);
            }
        }
    };

if (logLevel !== 'none') {
if (
self.logger.warning &&
Expand All @@ -26,36 +37,37 @@ function Logger(config) {
}
};

this.error = function(msg) {
this.error = function(msg: string) {
if (logLevel !== 'none') {
if (self.logger.error) {
self.logger.error(msg);
}
}
};

this.setLogLevel = function(newLogLevel) {
this.setLogLevel = function(newLogLevel: string) {
logLevel = newLogLevel;
this.logLevel = logLevel;
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think you should be able to get rid of the redundant assignment and simplify this:

this.setLogLevel = function(_logLevel: string) {
        this.logLevel = _logLevel;

};
}

function ConsoleLogger() {
this.verbose = function(msg) {
function ConsoleLogger(this: Logger): void {
this.verbose = function(msg: string) {
if (console && console.info) {
console.info(msg);
}
};

this.error = function(msg) {
this.error = function(msg: string) {
if (console && console.error) {
console.error(msg);
}
};
this.warning = function(msg) {
this.warning = function(msg: string) {
if (console && console.warn) {
console.warn(msg);
}
};
}

export default Logger;
export default Logger;
8 changes: 4 additions & 4 deletions src/roktManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { IMParticleUser } from "./identity-user-interfaces";
import KitFilterHelper from "./kitFilterHelper";
import { Dictionary, parseSettingsString, generateUniqueId, isFunction } from "./utils";
import { SDKIdentityApi } from "./identity.interfaces";
import { SDKLoggerApi } from "./sdkRuntimeModels";
import Logger from "./logger";

// https://docs.rokt.com/developers/integration-guides/web/library/attributes
export interface IRoktPartnerAttributes {
Expand Down Expand Up @@ -84,15 +84,15 @@ export default class RoktManager {
private placementAttributesMapping: Dictionary<string>[] = [];
private identityService: SDKIdentityApi;
private launcherOptions?: IRoktLauncherOptions;
private logger: SDKLoggerApi;
private logger: Logger;
private domain?: string;
/**
* Initializes the RoktManager with configuration settings and user data.
*
* @param {IKitConfigs} roktConfig - Configuration object containing user attribute filters and settings
* @param {IMParticleUser} filteredUser - User object with filtered attributes
* @param {SDKIdentityApi} identityService - The mParticle Identity instance
* @param {SDKLoggerApi} logger - The mParticle Logger instance
* @param {Logger} logger - The mParticle Logger instance
* @param {IRoktOptions} options - Options for the RoktManager
*
* @throws Logs error to console if placementAttributesMapping parsing fails
Expand All @@ -101,7 +101,7 @@ export default class RoktManager {
roktConfig: IKitConfigs,
filteredUser: IMParticleUser,
identityService: SDKIdentityApi,
logger?: SDKLoggerApi,
logger?: Logger,
options?: IRoktOptions
): void {
const { userAttributeFilters, settings } = roktConfig || {};
Expand Down
10 changes: 2 additions & 8 deletions src/sdkRuntimeModels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Dictionary, valueof } from './utils';
import { IKitConfigs } from './configAPIClient';
import { SDKConsentApi, SDKConsentState } from './consent';
import MPSideloadedKit from './sideloadedKit';
import Logger from './logger'
import { ISessionManager } from './sessionManager';
import { ConfiguredKit, MPForwarder, UnregisteredKit } from './forwarders.interfaces';
import {
Expand Down Expand Up @@ -172,7 +173,7 @@ export interface MParticleWebSDK {
PromotionType: typeof PromotionActionType;
ProductActionType: typeof ProductActionType;
Identity: SDKIdentityApi;
Logger: SDKLoggerApi;
Logger: Logger;
Consent: SDKConsentApi;
_resetForTests(
MPConfig?: SDKInitConfig,
Expand Down Expand Up @@ -352,13 +353,6 @@ export interface SDKHelpersApi {
Validators: typeof Validators;
}

export interface SDKLoggerApi {
error(arg0: string): void;
verbose(arg0: string): void;
warning(arg0: string): void;
setLogLevel(logLevel: LogLevelType): void;
}

// TODO: Merge this with IStore in store.ts
export interface SDKStoreApi {
isEnabled: boolean;
Expand Down
61 changes: 61 additions & 0 deletions test/jest/logger.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import Logger from "../../src/logger";
import { SDKInitConfig } from "../../src/sdkRuntimeModels";

describe('ConsoleLogger', () => {
it('should set logger level to warning', () => {
// create a dummy config
let sampleConfig = {
appName: 'Store Test',
appVersion: '1.x',
package: 'com.mparticle.test',
flags: {},
} as SDKInitConfig;

// create a new Logger instance
const logger = new Logger(sampleConfig);

// setLogLevel to warning
logger.setLogLevel('warning');

// insure the logLevel is set to warning
expect(logger.logLevel).toBe('warning')
});

it('should set logger level to verbose', () => {
// create a dummy config
let sampleConfig = {
appName: 'Store Test',
appVersion: '1.x',
package: 'com.mparticle.test',
flags: {},
} as SDKInitConfig;

// create a new Logger instance
const logger = new Logger(sampleConfig);

// setLogLevel to verbose
logger.setLogLevel('verbose');

// insure the logLevel is set to verbose
expect(logger.logLevel).toBe('verbose')
})

it('should set logger level to error', () => {
// create a dummy config
let sampleConfig = {
appName: 'Store Test',
appVersion: '1.x',
package: 'com.mparticle.test',
flags: {},
} as SDKInitConfig;

// create a new Logger instance
const logger = new Logger(sampleConfig);

// setLogLevel to error
logger.setLogLevel('error');

// insure the logLevel is set to error
expect(logger.logLevel).toBe('error')
})
});
6 changes: 3 additions & 3 deletions test/src/tests-audience-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import fetchMock from 'fetch-mock/esm/client';
import { expect } from 'chai';
import { urls, apiKey, testMPID } from './config/constants';
import Constants from '../../src/constants';
import { IMParticleInstanceManager, SDKLoggerApi } from '../../src/sdkRuntimeModels';
import { IMParticleInstanceManager } from '../../src/sdkRuntimeModels';
import AudienceManager, {
IAudienceMemberships, IAudienceMembershipsServerResponse
} from '../../src/audienceManager';
import Logger from '../../src/logger.js';
import Logger from '../../src/logger';
import Utils from './config/utils';
const { fetchMockSuccess } = Utils;

Expand Down Expand Up @@ -45,7 +45,7 @@ describe('AudienceManager', () => {

describe('initialization', () => {
it('should have proper properties on AudienceManager', () => {
const newLogger: SDKLoggerApi = new Logger(window.mParticle.config);
const newLogger: Logger = new Logger(window.mParticle.config);
const audienceManager = new AudienceManager(
Constants.DefaultBaseUrls.userAudienceUrl,
apiKey,
Expand Down
Loading