configuration.js 1.7 KB

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