Skip to content

Commit f1a4155

Browse files
Don't show redundant level when using custom logger
1 parent 26d12ef commit f1a4155

File tree

7 files changed

+57
-54
lines changed

7 files changed

+57
-54
lines changed

src/logger/__tests__/index.spec.ts

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@ const LOG_LEVELS_IN_ORDER: SplitIO.LogLevel[] = ['DEBUG', 'INFO', 'WARN', 'ERROR
3838
/* Utility function to avoid repeating too much code */
3939
function testLogLevels(levelToTest: SplitIO.LogLevel) {
4040
// Builds the expected message.
41-
const buildExpectedMessage = (lvl: string, category: string, msg: string, showLevel?: boolean) => {
41+
const buildExpectedMessage = (lvl: string, category: string, msg: string, useDefaultLogger?: boolean) => {
4242
let res = '';
43-
if (showLevel) res += '[' + lvl + ']' + (lvl.length === 4 ? ' ' : ' ');
43+
if (useDefaultLogger) res += '[' + lvl + ']' + (lvl.length === 4 ? ' ' : ' ');
4444
res += category + ' => ';
4545
res += msg;
4646
return res;
@@ -49,24 +49,33 @@ function testLogLevels(levelToTest: SplitIO.LogLevel) {
4949
// Spy console.log
5050
const consoleLogSpy = jest.spyOn(global.console, 'log');
5151

52-
// Runs the suite with the given value for showLevel option.
53-
const runTests = (showLevel?: boolean, useCodes?: boolean) => {
52+
// Runs the suite with the given values
53+
const runTests = (useDefaultLogger?: boolean, useCodes?: boolean) => {
5454
let logLevelLogsCounter = 0;
5555
let testForNoLog = false;
5656
const logMethod = levelToTest.toLowerCase();
5757
const logCategory = `test-category-${logMethod}`;
58-
const instance = new Logger({ prefix: logCategory, showLevel },
59-
useCodes ? new Map([[1, 'Test log for level %s with showLevel: %s %s']]) : undefined);
58+
const instance = new Logger({ prefix: logCategory },
59+
useCodes ? new Map([[1, 'Test log for level %s with default logger: %s %s']]) : undefined);
60+
if (!useDefaultLogger) {
61+
instance.setLogger({
62+
debug: console.log,
63+
info: console.log,
64+
warn: console.log,
65+
error: console.log,
66+
});
67+
}
68+
6069

6170
LOG_LEVELS_IN_ORDER.forEach((logLevel, i) => {
62-
const logMsg = `Test log for level ${levelToTest} with showLevel: ${showLevel} ${logLevelLogsCounter}`;
63-
const expectedMessage = buildExpectedMessage(levelToTest, logCategory, logMsg, showLevel);
71+
const logMsg = `Test log for level ${levelToTest} with default logger: ${useDefaultLogger} ${logLevelLogsCounter}`;
72+
const expectedMessage = buildExpectedMessage(levelToTest, logCategory, logMsg, useDefaultLogger);
6473

6574
// Set the logLevel for this iteration.
6675
instance.setLogLevel(LogLevels[logLevel]);
6776
// Call the method
6877
// @ts-ignore
69-
if (useCodes) instance[logMethod](1, [levelToTest, showLevel, logLevelLogsCounter]); // @ts-ignore
78+
if (useCodes) instance[logMethod](1, [levelToTest, useDefaultLogger, logLevelLogsCounter]); // @ts-ignore
7079
else instance[logMethod](logMsg);
7180
// Assert if console.log was called.
7281
const actualMessage = consoleLogSpy.mock.calls[consoleLogSpy.mock.calls.length - 1][0];
@@ -83,11 +92,11 @@ function testLogLevels(levelToTest: SplitIO.LogLevel) {
8392
});
8493
};
8594

86-
// Show logLevel
95+
// Default console.log (Show level in logs)
8796
runTests(true);
88-
// Hide logLevel
97+
// Custom logger (Don't show level in logs)
8998
runTests(false);
90-
// Hide logLevel and use message codes
99+
// Custom logger (Don't show level in logs) and use message codes
91100
runTests(false, true);
92101

93102
// Restore spied object.

src/logger/__tests__/sdkLogger.spec.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ test('LoggerAPI / methods and props', () => {
3030
API.setLogger(console);
3131
expect(getCustomLogger(logger)).toBe(console);
3232

33+
// unset custom logger
34+
API.setLogger(undefined);
35+
expect(getCustomLogger(logger)).toBeUndefined();
36+
3337
// invalid custom logger
3438
// @ts-expect-error
3539
API.setLogger({});

src/logger/index.ts

Lines changed: 20 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,13 @@ const LogLevelIndexes = {
2020
NONE: 5
2121
};
2222

23+
const DEFAULT_LOGGER: SplitIO.Logger = {
24+
debug(msg) { console.log('[DEBUG] ' + msg); },
25+
info(msg) { console.log('[INFO] ' + msg); },
26+
warn(msg) { console.log('[WARN] ' + msg); },
27+
error(msg) { console.log('[ERROR] ' + msg); }
28+
};
29+
2330
export function isLogLevelString(str: string): str is SplitIO.LogLevel {
2431
return !!find(LogLevels, (lvl: string) => str === lvl);
2532
}
@@ -41,7 +48,6 @@ export function _sprintf(format: string = '', args: any[] = []): string {
4148
const defaultOptions = {
4249
prefix: 'splitio',
4350
logLevel: LogLevels.NONE,
44-
showLevel: true,
4551
};
4652

4753
export class Logger implements ILogger {
@@ -68,63 +74,48 @@ export class Logger implements ILogger {
6874
this.logger = logger;
6975
// If custom logger is set, all logs are either enabled or disabled
7076
if (this.logLevel !== LogLevelIndexes.NONE) this.setLogLevel(LogLevels.DEBUG);
77+
return;
7178
} else {
72-
this._log(LogLevels.ERROR, 'Invalid `logger` instance. It must be an object with `debug`, `info`, `warn` and `error` methods. Defaulting to `console.log`');
73-
this.logger = undefined;
79+
this.error('Invalid `logger` instance. It must be an object with `debug`, `info`, `warn` and `error` methods. Defaulting to `console.log`');
7480
}
7581
}
82+
// unset
83+
this.logger = undefined;
7684
}
7785

7886
debug(msg: string | number, args?: any[]) {
79-
if (this._shouldLog(LogLevelIndexes.DEBUG)) this._log(LogLevels.DEBUG, msg, args);
87+
if (this._shouldLog(LogLevelIndexes.DEBUG)) this._log('debug', msg, args);
8088
}
8189

8290
info(msg: string | number, args?: any[]) {
83-
if (this._shouldLog(LogLevelIndexes.INFO)) this._log(LogLevels.INFO, msg, args);
91+
if (this._shouldLog(LogLevelIndexes.INFO)) this._log('info', msg, args);
8492
}
8593

8694
warn(msg: string | number, args?: any[]) {
87-
if (this._shouldLog(LogLevelIndexes.WARN)) this._log(LogLevels.WARN, msg, args);
95+
if (this._shouldLog(LogLevelIndexes.WARN)) this._log('warn', msg, args);
8896
}
8997

9098
error(msg: string | number, args?: any[]) {
91-
if (this._shouldLog(LogLevelIndexes.ERROR)) this._log(LogLevels.ERROR, msg, args);
99+
if (this._shouldLog(LogLevelIndexes.ERROR)) this._log('error', msg, args);
92100
}
93101

94-
private _log(level: SplitIO.LogLevel, msg: string | number, args?: any[]) {
102+
_log(method: keyof SplitIO.Logger, msg: string | number, args?: any[]) {
95103
if (typeof msg === 'number') {
96104
const format = this.codes.get(msg);
97105
msg = format ? _sprintf(format, args) : `Message code ${msg}${args ? ', with args: ' + args.toString() : ''}`;
98106
} else {
99107
if (args) msg = _sprintf(msg, args);
100108
}
101109

102-
const formattedText = this._generateLogMessage(level, msg);
110+
if (this.options.prefix) msg = this.options.prefix + ' => ' + msg;
103111

104-
// Do not break on custom logger errors
105112
if (this.logger) {
106-
try { // @ts-expect-error
107-
this.logger[level.toLowerCase()](formattedText);
113+
try {
114+
this.logger[method](msg);
108115
return;
109116
} catch (e) { /* empty */ }
110117
}
111-
112-
console.log(formattedText);
113-
}
114-
115-
private _generateLogMessage(level: SplitIO.LogLevel, text: string) {
116-
const textPre = ' => ';
117-
let result = '';
118-
119-
if (this.options.showLevel) {
120-
result += '[' + level + ']' + (level === LogLevels.INFO || level === LogLevels.WARN ? ' ' : '') + ' ';
121-
}
122-
123-
if (this.options.prefix) {
124-
result += this.options.prefix + textPre;
125-
}
126-
127-
return result += text;
118+
DEFAULT_LOGGER[method](msg);
128119
}
129120

130121
private _shouldLog(level: number) {

src/logger/types.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import SplitIO from '../../types/splitio';
33
export interface ILoggerOptions {
44
prefix?: string;
55
logLevel?: SplitIO.LogLevel;
6-
showLevel?: boolean; // @TODO remove this param eventually since it is not being set `false` anymore
76
}
87

98
export interface ILogger extends SplitIO.ILogger {

src/utils/settingsValidation/logger/__tests__/index.spec.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,16 +76,16 @@ describe('logger validators', () => {
7676
const logger = validateLogger({ debug: true, logger: customLogger });
7777

7878
logger.debug('test debug');
79-
expect(customLogger.debug).toBeCalledWith('[DEBUG] splitio => test debug');
79+
expect(customLogger.debug).toBeCalledWith('splitio => test debug');
8080

8181
logger.info('test info');
82-
expect(customLogger.info).toBeCalledWith('[INFO] splitio => test info');
82+
expect(customLogger.info).toBeCalledWith('splitio => test info');
8383

8484
logger.warn('test warn');
85-
expect(customLogger.warn).toBeCalledWith('[WARN] splitio => test warn');
85+
expect(customLogger.warn).toBeCalledWith('splitio => test warn');
8686

8787
logger.error('test error');
88-
expect(customLogger.error).toBeCalledWith('[ERROR] splitio => test error');
88+
expect(customLogger.error).toBeCalledWith('splitio => test error');
8989

9090
expect(consoleLogSpy).not.toBeCalled();
9191
});
@@ -121,19 +121,19 @@ describe('logger validators', () => {
121121
const logger = validateLogger({ debug: true, logger: customLoggerWithErrors });
122122

123123
logger.debug('test debug');
124-
expect(customLoggerWithErrors.debug).toBeCalledWith('[DEBUG] splitio => test debug');
124+
expect(customLoggerWithErrors.debug).toBeCalledWith('splitio => test debug');
125125
expect(consoleLogSpy).toBeCalledWith('[DEBUG] splitio => test debug');
126126

127127
logger.info('test info');
128-
expect(customLoggerWithErrors.info).toBeCalledWith('[INFO] splitio => test info');
128+
expect(customLoggerWithErrors.info).toBeCalledWith('splitio => test info');
129129
expect(consoleLogSpy).toBeCalledWith('[INFO] splitio => test info');
130130

131131
logger.warn('test warn');
132-
expect(customLoggerWithErrors.warn).toBeCalledWith('[WARN] splitio => test warn');
132+
expect(customLoggerWithErrors.warn).toBeCalledWith('splitio => test warn');
133133
expect(consoleLogSpy).toBeCalledWith('[WARN] splitio => test warn');
134134

135135
logger.error('test error');
136-
expect(customLoggerWithErrors.error).toBeCalledWith('[ERROR] splitio => test error');
136+
expect(customLoggerWithErrors.error).toBeCalledWith('splitio => test error');
137137
expect(consoleLogSpy).toBeCalledWith('[ERROR] splitio => test error');
138138

139139
expect(consoleLogSpy).toBeCalledTimes(4);

src/utils/settingsValidation/logger/builtinLogger.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ export function validateLogger(settings: { debug: unknown, logger?: SplitIO.Logg
4848
const log = new Logger({ logLevel: logLevel || initialLogLevel }, allCodes);
4949
log.setLogger(logger);
5050

51-
// @ts-ignore // if logLevel is undefined at this point, it means that settings `debug` value is invalid
52-
if (!logLevel) log._log(LogLevels.ERROR, 'Invalid Log Level - No changes to the logs will be applied.');
51+
// if logLevel is undefined at this point, it means that settings `debug` value is invalid
52+
if (!logLevel) log._log('error', 'Invalid Log Level - No changes to the logs will be applied.');
5353

5454
return log;
5555
}

src/utils/settingsValidation/logger/pluggableLogger.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ export function validateLogger(settings: { debug: unknown, logger?: SplitIO.Logg
3232
const log = new Logger({ logLevel: logLevel || initialLogLevel });
3333
log.setLogger(logger);
3434

35-
// @ts-ignore // `debug` value is invalid if logLevel is undefined at this point
36-
if (!logLevel) log._log(LogLevels.ERROR, 'Invalid `debug` value at config. Logs will be disabled.');
35+
// `debug` value is invalid if logLevel is undefined at this point
36+
if (!logLevel) log._log('error', 'Invalid `debug` value at config. Logs will be disabled.');
3737

3838
return log;
3939
}

0 commit comments

Comments
 (0)