From b1c33b279c6ec785b21160f3b9f05e9419f3afcc Mon Sep 17 00:00:00 2001 From: Homa Wong Date: Tue, 20 Feb 2018 13:54:31 -0800 Subject: [PATCH] feat: add onDebug overload This support the most common usage. --- README.md | 3 +++ src/Logger.ts | 7 +++++-- src/getLogger.spec.ts | 15 +++++++++++++++ src/interfaces.ts | 8 ++++---- 4 files changed, 27 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 600ec66..852276b 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,9 @@ log.onWarn(...) log.onInfo(...) log.onDebug(...) +// or +log.onError(() => getLogMessageThatIsTimeConsumingToCreate()) + function getLogMessageThatIsTimeConsumingToCreate() { ... } diff --git a/src/Logger.ts b/src/Logger.ts index 2f40460..9170b6c 100644 --- a/src/Logger.ts +++ b/src/Logger.ts @@ -50,7 +50,10 @@ export class LoggerImpl implements ALogger { } private on(logLevel, logFunction) { - if (this.level >= logLevel) - logFunction(this.logger[logLevelNameMap[logLevel]].bind(this.logger)) + if (this.level >= logLevel) { + const logFn = this.logger[logLevelNameMap[logLevel]].bind(this.logger) + const result = logFunction(logFn) + if (result) logFn(result) + } } } diff --git a/src/getLogger.spec.ts b/src/getLogger.spec.ts index f2a4a94..384b5bb 100644 --- a/src/getLogger.spec.ts +++ b/src/getLogger.spec.ts @@ -267,3 +267,18 @@ test('on???() logs to corresponding log', t => { 'error' ]) }) + +test(`pass '() => string' into on???() will log the result`, t => { + const log = getLogger('onXXX with () => string') + log.setLevel(logLevel.debug) + log.onDebug(() => 'debug') + log.onInfo(() => 'info') + log.onWarn(() => 'warn') + log.onError(() => 'error') + t.deepEqual(appender.logs.map(l => l.messages[0]), [ + 'debug', + 'info', + 'warn', + 'error' + ]) +}) diff --git a/src/interfaces.ts b/src/interfaces.ts index 76e20ad..f002503 100644 --- a/src/interfaces.ts +++ b/src/interfaces.ts @@ -9,8 +9,8 @@ export interface Logger extends ALogger { error(...args: any[]): void setLevel(level: number): void - onError(logFunction: (log: logMethod) => void): void - onWarn(logFunction: (log: logMethod) => void): void - onInfo(logFunction: (log: logMethod) => void): void - onDebug(logFunction: (log: logMethod) => void): void + onError(logFunction: ((log: logMethod) => void) | (() => string)): void + onWarn(logFunction: ((log: logMethod) => void) | (() => string)): void + onInfo(logFunction: ((log: logMethod) => void) | (() => string)): void + onDebug(logFunction: ((log: logMethod) => void) | (() => string)): void }