diff --git a/lib/logger.js b/lib/logger.js index 511e8a6f47..9d573da390 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -9,7 +9,17 @@ module.exports = exports = function getLogger(name) { }; exports.setLoggerProvider = function setLoggerProvider(provider) { + validate(typeof provider == 'function', 'Provider needs to be a function'); + + const logger = provider('unleash:logger'); + + validate(typeof logger.debug == 'function', 'Logger must implement debug'); + validate(typeof logger.info == 'function', 'Logger must implement info'); + validate(typeof logger.warn == 'function', 'Logger must implement warn'); + validate(typeof logger.error == 'function', 'Logger must implement error'); + loggerProvider = provider; + logger.info('Custom Logger Provider initalized.'); }; function getDefaultLogProvider() { @@ -31,3 +41,9 @@ function getDefaultLogProvider() { return log4js.getLogger; } + +function validate(isValid, msg) { + if (!isValid) { + throw new TypeError(msg); + } +} diff --git a/lib/logger.test.js b/lib/logger.test.js index 0ceea9f73f..b24adb421d 100644 --- a/lib/logger.test.js +++ b/lib/logger.test.js @@ -3,20 +3,49 @@ const { test } = require('ava'); const createLogger = require('./logger'); const logger = require('../logger'); -const sinon = require('sinon'); test('should expose a setLoggerProvider function', t => { t.true(logger.setLoggerProvider instanceof Function); }); test('should create logger via custom logger provider', t => { - const provider = sinon.stub(); const loggerName = 'test'; - const loggerImpl = {}; - provider.withArgs(loggerName).returns(loggerImpl); + const loggerImpl = { + debug: () => {}, + info: () => {}, + warn: () => {}, + error: () => {}, + }; + const provider = () => loggerImpl; logger.setLoggerProvider(provider); const log = createLogger(loggerName); t.is(log, loggerImpl); }); + +test('should require custom logger to implement info', t => { + const loggerImpl = { + debug: () => {}, + warn: () => {}, + error: () => {}, + }; + const provider = () => loggerImpl; + const error = t.throws(() => { + logger.setLoggerProvider(provider)(); + }, TypeError); + t.is(error.message, 'Logger must implement info'); +}); + +test('should require custom logger to implement error', t => { + const loggerImpl = { + debug: () => {}, + warn: () => {}, + info: () => {}, + }; + const provider = () => loggerImpl; + const error = t.throws(() => { + logger.setLoggerProvider(provider)(); + }, TypeError); + t.is(error.message, 'Logger must implement error'); +});