log4js.js 3.9 KB

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