logger.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* eslint no-underscore-dangle:0 */
  2. 'use strict';
  3. const debug = require('debug')('log4js:logger');
  4. const LoggingEvent = require('./LoggingEvent');
  5. const levels = require('./levels');
  6. const clustering = require('./clustering');
  7. const categories = require('./categories');
  8. const configuration = require('./configuration');
  9. /**
  10. * Logger to log messages.
  11. * use {@see log4js#getLogger(String)} to get an instance.
  12. *
  13. * @name Logger
  14. * @namespace Log4js
  15. * @param name name of category to log to
  16. * @param level - the loglevel for the category
  17. * @param dispatch - the function which will receive the logevents
  18. *
  19. * @author Stephan Strittmatter
  20. */
  21. class Logger {
  22. constructor(name) {
  23. if (!name) {
  24. throw new Error('No category provided.');
  25. }
  26. this.category = name;
  27. this.context = {};
  28. debug(`Logger created (${this.category}, ${this.level})`);
  29. }
  30. get level() {
  31. return levels.getLevel(categories.getLevelForCategory(this.category), levels.TRACE);
  32. }
  33. set level(level) {
  34. categories.setLevelForCategory(this.category, levels.getLevel(level, this.level));
  35. }
  36. log(level, ...args) {
  37. const logLevel = levels.getLevel(level, levels.INFO);
  38. if (this.isLevelEnabled(logLevel)) {
  39. this._log(logLevel, args);
  40. }
  41. }
  42. isLevelEnabled(otherLevel) {
  43. return this.level.isLessThanOrEqualTo(otherLevel);
  44. }
  45. _log(level, data) {
  46. debug(`sending log data (${level}) to appenders`);
  47. const loggingEvent = new LoggingEvent(this.category, level, data, this.context);
  48. clustering.send(loggingEvent);
  49. }
  50. addContext(key, value) {
  51. this.context[key] = value;
  52. }
  53. removeContext(key) {
  54. delete this.context[key];
  55. }
  56. clearContext() {
  57. this.context = {};
  58. }
  59. }
  60. function addLevelMethods(target) {
  61. const level = levels.getLevel(target);
  62. const levelStrLower = level.toString().toLowerCase();
  63. const levelMethod = levelStrLower.replace(/_([a-z])/g, g => g[1].toUpperCase());
  64. const isLevelMethod = levelMethod[0].toUpperCase() + levelMethod.slice(1);
  65. Logger.prototype[`is${isLevelMethod}Enabled`] = function () {
  66. return this.isLevelEnabled(level);
  67. };
  68. Logger.prototype[levelMethod] = function (...args) {
  69. this.log(level, ...args);
  70. };
  71. }
  72. levels.levels.forEach(addLevelMethods);
  73. configuration.addListener(() => {
  74. levels.levels.forEach(addLevelMethods);
  75. });
  76. module.exports = Logger;