configuration.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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) =>
  7. 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) =>
  10. thing && typeof thing === 'number' && Number.isInteger(thing);
  11. const addListener = (fn) => {
  12. listeners.push(fn);
  13. debug(`Added listener, now ${listeners.length} listeners`);
  14. };
  15. const addPreProcessingListener = (fn) => {
  16. preProcessingListeners.push(fn);
  17. debug(
  18. `Added pre-processing listener, now ${preProcessingListeners.length} listeners`
  19. );
  20. };
  21. const throwExceptionIf = (config, checks, message) => {
  22. const tests = Array.isArray(checks) ? checks : [checks];
  23. tests.forEach((test) => {
  24. if (test) {
  25. throw new Error(
  26. `Problem with log4js configuration: (${util.inspect(config, {
  27. depth: 5,
  28. })}) - ${message}`
  29. );
  30. }
  31. });
  32. };
  33. const configure = (candidate) => {
  34. debug('New configuration to be validated: ', candidate);
  35. throwExceptionIf(candidate, not(anObject(candidate)), 'must be an object.');
  36. debug(`Calling pre-processing listeners (${preProcessingListeners.length})`);
  37. preProcessingListeners.forEach((listener) => listener(candidate));
  38. debug('Configuration pre-processing finished.');
  39. debug(`Calling configuration listeners (${listeners.length})`);
  40. listeners.forEach((listener) => listener(candidate));
  41. debug('Configuration finished.');
  42. };
  43. module.exports = {
  44. configure,
  45. addListener,
  46. addPreProcessingListener,
  47. throwExceptionIf,
  48. anObject,
  49. anInteger,
  50. validIdentifier,
  51. not,
  52. };