diff --git a/src/logger.ts b/src/logger.ts index 473955245c..db67bba40b 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -587,6 +587,22 @@ export class Logger { return this; } + /** + * Logs at `debug` level with filtering applied. + * + * @param cb A callback that returns on array objects to be logged. + */ + public debugCallback(cb: () => Array | string) { + if (this.getLevel() === LoggerLevel.DEBUG || process.env.DEBUG) { + const result = cb(); + if (isArray(result)) { + this.bunyan.debug(this.applyFilters(LoggerLevel.DEBUG, ...result)); + } else { + this.bunyan.debug(this.applyFilters(LoggerLevel.DEBUG, ...[result])); + } + } + } + /** * Logs at `info` level with filtering applied. For convenience `this` object is returned. * diff --git a/test/unit/loggerTest.ts b/test/unit/loggerTest.ts index 159a56c87b..9fea99306d 100644 --- a/test/unit/loggerTest.ts +++ b/test/unit/loggerTest.ts @@ -168,6 +168,29 @@ describe('Logger', () => { }); }); + describe('debugCallback', () => { + it('should log', async () => { + const logger = (await Logger.child('testLogger')).useMemoryLogging(); + logger.setLevel(LoggerLevel.DEBUG); + const FOO = 'foo'; + const BAR = 'bar'; + const spy = $$.SANDBOX.spy(() => [FOO, BAR]); + logger.debugCallback(spy); + expect(spy.callCount).to.be.equal(1); + expect(logger.readLogContentsAsText()) + .to.include(FOO) + .and.to.include(BAR); + }); + + it("shouldn't log", async () => { + const logger = (await Logger.child('testLogger')).useMemoryLogging(); + const fooSpy = $$.SANDBOX.spy(() => 'FOO'); + const cbSpy = $$.SANDBOX.spy(() => `${fooSpy()}`); + logger.debugCallback(cbSpy); + expect(fooSpy.callCount).to.be.equal(0); + expect(cbSpy.callCount).to.be.equal(0); + }); + }); describe('filters', () => { const sid = 'SIDHERE!'; const simpleString = `sid=${sid}`;