configuration.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict';
  2. const util = require('util');
  3. const debug = require('debug')('log4js:configuration');
  4. const preProcessingListeners = [];
  5. const listeners = [];
  6. const not = thing => !thing;
  7. const anObject = thing => thing && typeof thing === 'object' && !Array.isArray(thing);
  8. const validIdentifier = thing => /^[A-Za-z][A-Za-z0-9_]*$/g.test(thing);
  9. const anInteger = thing => thing && typeof thing === 'number' && Number.isInteger(thing);
  10. const addListener = (fn) => {
  11. listeners.push(fn);
  12. debug(`Added listener, now ${listeners.length} listeners`);
  13. };
  14. const addPreProcessingListener = (fn) => {
  15. preProcessingListeners.push(fn);
  16. debug(`Added pre-processing listener, now ${preProcessingListeners.length} listeners`);
  17. };
  18. const throwExceptionIf = (config, checks, message) => {
  19. const tests = Array.isArray(checks) ? checks : [checks];
  20. tests.forEach((test) => {
  21. if (test) {
  22. throw new Error(`Problem with log4js configuration: (${util.inspect(config, { depth: 5 })})`
  23. + ` - ${message}`);
  24. }
  25. });
  26. };
  27. const configure = (candidate) => {
  28. debug('New configuration to be validated: ', candidate);
  29. throwExceptionIf(candidate, not(anObject(candidate)), 'must be an object.');
  30. debug(`Calling pre-processing listeners (${preProcessingListeners.length})`);
  31. preProcessingListeners.forEach(listener => listener(candidate));
  32. debug('Configuration pre-processing finished.');
  33. debug(`Calling configuration listeners (${listeners.length})`);
  34. listeners.forEach(listener => listener(candidate));
  35. debug('Configuration finished.');
  36. };
  37. module.exports = {
  38. configure,
  39. addListener,
  40. addPreProcessingListener,
  41. throwExceptionIf,
  42. anObject,
  43. anInteger,
  44. validIdentifier,
  45. not
  46. };