log4js.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /**
  2. * @fileoverview log4js is a library to log in JavaScript in similar manner
  3. * than in log4j for Java (but not really).
  4. *
  5. * <h3>Example:</h3>
  6. * <pre>
  7. * const logging = require('log4js');
  8. * const log = logging.getLogger('some-category');
  9. *
  10. * //call the log
  11. * log.trace('trace me' );
  12. * </pre>
  13. *
  14. * NOTE: the authors below are the original browser-based log4js authors
  15. * don't try to contact them about bugs in this version :)
  16. * @author Stephan Strittmatter - http://jroller.com/page/stritti
  17. * @author Seth Chisamore - http://www.chisamore.com
  18. * @since 2005-05-20
  19. * Website: http://log4js.berlios.de
  20. */
  21. const debug = require("debug")("log4js:main");
  22. const fs = require("fs");
  23. const deepClone = require("rfdc")({ proto: true });
  24. const configuration = require("./configuration");
  25. const layouts = require("./layouts");
  26. const levels = require("./levels");
  27. const appenders = require("./appenders");
  28. const categories = require("./categories");
  29. const Logger = require("./logger");
  30. const clustering = require("./clustering");
  31. const connectLogger = require("./connect-logger");
  32. const recordingModule = require("./appenders/recording");
  33. let enabled = false;
  34. function sendLogEventToAppender(logEvent) {
  35. if (!enabled) return;
  36. debug("Received log event ", logEvent);
  37. const categoryAppenders = categories.appendersForCategory(
  38. logEvent.categoryName
  39. );
  40. categoryAppenders.forEach(appender => {
  41. appender(logEvent);
  42. });
  43. }
  44. function loadConfigurationFile(filename) {
  45. debug(`Loading configuration from ${filename}`);
  46. try {
  47. return JSON.parse(fs.readFileSync(filename, "utf8"));
  48. } catch (e) {
  49. throw new Error(
  50. `Problem reading config from file "${filename}". Error was ${e.message}`,
  51. e
  52. );
  53. }
  54. }
  55. function configure(configurationFileOrObject) {
  56. if (enabled) {
  57. // eslint-disable-next-line no-use-before-define
  58. shutdown();
  59. }
  60. let configObject = configurationFileOrObject;
  61. if (typeof configObject === "string") {
  62. configObject = loadConfigurationFile(configurationFileOrObject);
  63. }
  64. debug(`Configuration is ${configObject}`);
  65. configuration.configure(deepClone(configObject));
  66. clustering.onMessage(sendLogEventToAppender);
  67. enabled = true;
  68. // eslint-disable-next-line no-use-before-define
  69. return log4js;
  70. }
  71. function recording() {
  72. return recordingModule
  73. }
  74. /**
  75. * Shutdown all log appenders. This will first disable all writing to appenders
  76. * and then call the shutdown function each appender.
  77. *
  78. * @params {Function} cb - The callback to be invoked once all appenders have
  79. * shutdown. If an error occurs, the callback will be given the error object
  80. * as the first argument.
  81. */
  82. function shutdown(cb) {
  83. debug("Shutdown called. Disabling all log writing.");
  84. // First, disable all writing to appenders. This prevents appenders from
  85. // not being able to be drained because of run-away log writes.
  86. enabled = false;
  87. // Clone out to maintain a reference
  88. const appendersToCheck = Array.from(appenders.values());
  89. // Reset immediately to prevent leaks
  90. appenders.init();
  91. categories.init();
  92. // Call each of the shutdown functions in parallel
  93. const shutdownFunctions = appendersToCheck.reduceRight(
  94. (accum, next) => (next.shutdown ? accum + 1 : accum),
  95. 0
  96. );
  97. if (shutdownFunctions === 0) {
  98. debug("No appenders with shutdown functions found.");
  99. return cb !== undefined && cb();
  100. }
  101. let completed = 0;
  102. let error;
  103. debug(`Found ${shutdownFunctions} appenders with shutdown functions.`);
  104. function complete(err) {
  105. error = error || err;
  106. completed += 1;
  107. debug(`Appender shutdowns complete: ${completed} / ${shutdownFunctions}`);
  108. if (completed >= shutdownFunctions) {
  109. debug("All shutdown functions completed.");
  110. if (cb) {
  111. cb(error);
  112. }
  113. }
  114. }
  115. appendersToCheck.filter(a => a.shutdown).forEach(a => a.shutdown(complete));
  116. return null;
  117. }
  118. /**
  119. * Get a logger instance.
  120. * @static
  121. * @param loggerCategoryName
  122. * @return {Logger} instance of logger for the category
  123. */
  124. function getLogger(category) {
  125. if (!enabled) {
  126. configure(
  127. process.env.LOG4JS_CONFIG || {
  128. appenders: { out: { type: "stdout" } },
  129. categories: { default: { appenders: ["out"], level: "OFF" } }
  130. }
  131. );
  132. }
  133. return new Logger(category || "default");
  134. }
  135. /**
  136. * @name log4js
  137. * @namespace Log4js
  138. * @property getLogger
  139. * @property configure
  140. * @property shutdown
  141. */
  142. const log4js = {
  143. getLogger,
  144. configure,
  145. shutdown,
  146. connectLogger,
  147. levels,
  148. addLayout: layouts.addLayout,
  149. recording,
  150. };
  151. module.exports = log4js;