Logger.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*
  2. Журналирование с буферизацией вывода
  3. */
  4. const fs = require('fs-extra');
  5. const ayncExit = new (require('./AsyncExit'))();
  6. const sleep = (ms) => { return new Promise(resolve => setTimeout(resolve, ms)) };
  7. global.LM_OK = 0;
  8. global.LM_INFO = 1;
  9. global.LM_WARN = 2;
  10. global.LM_ERR = 3;
  11. global.LM_FATAL = 4;
  12. global.LM_TOTAL = 5;
  13. const LOG_CACHE_BUFFER_SIZE = 8192;
  14. const LOG_BUFFER_FLUSH_INTERVAL = 200;
  15. const LOG_ROTATE_FILE_LENGTH = 1000000;
  16. const LOG_ROTATE_FILE_DEPTH = 9;
  17. const LOG_ROTATE_FILE_CHECK_INTERVAL = 60000;
  18. let msgTypeToStr = {
  19. [LM_OK]: ' OK',
  20. [LM_INFO]: ' INFO',
  21. [LM_WARN]: ' WARN',
  22. [LM_ERR]: 'ERROR',
  23. [LM_FATAL]: 'FATAL ERROR',
  24. [LM_TOTAL]: 'TOTAL'
  25. };
  26. class BaseLog {
  27. constructor(params) {
  28. this.params = params;
  29. this.exclude = new Set(params.exclude);
  30. this.outputBufferLength = 0;
  31. this.outputBuffer = [];
  32. this.flushing = false;
  33. }
  34. async flush() {
  35. if (this.flushing || !this.outputBufferLength)
  36. return;
  37. this.flushing = true;
  38. this.data = this.outputBuffer;
  39. this.outputBufferLength = 0;
  40. this.outputBuffer = [];
  41. await this.flushImpl(this.data)
  42. .catch(e => { console.error(`Logger error: ${e}`); ayncExit.exit(1); } );
  43. this.flushing = false;
  44. }
  45. log(msgType, message) {
  46. if (this.closed)
  47. return;
  48. if (!this.exclude.has(msgType)) {
  49. this.outputBuffer.push(message);
  50. this.outputBufferLength += message.length;
  51. if (this.outputBufferLength >= LOG_CACHE_BUFFER_SIZE && !this.flushing) {
  52. this.flush();
  53. }
  54. if (!this.iid) {
  55. this.iid = setInterval(() => {
  56. if (!this.flushing) {
  57. clearInterval(this.iid);
  58. this.iid = 0;
  59. this.flush();
  60. }
  61. }, LOG_BUFFER_FLUSH_INTERVAL);
  62. }
  63. }
  64. }
  65. async close() {
  66. if (this.closed)
  67. return;
  68. if (this.iid)
  69. clearInterval(this.iid);
  70. try {
  71. while (this.outputBufferLength) {
  72. await this.flush();
  73. await sleep(1);
  74. }
  75. } catch(e) {
  76. console.log(e);
  77. ayncExit.exit(1);
  78. }
  79. this.outputBufferLength = 0;
  80. this.outputBuffer = [];
  81. this.closed = true;
  82. }
  83. }
  84. class FileLog extends BaseLog {
  85. constructor(params) {
  86. super(params);
  87. this.fileName = params.fileName;
  88. this.fd = fs.openSync(this.fileName, 'a');
  89. this.rcid = 0;
  90. }
  91. async close() {
  92. if (this.closed)
  93. return;
  94. await super.close();
  95. if (this.fd) {
  96. await fs.close(this.fd);
  97. this.fd = null;
  98. }
  99. if (this.rcid)
  100. clearTimeout(this.rcid);
  101. }
  102. async rotateFile(fileName, i) {
  103. let fn = fileName;
  104. if (i > 0)
  105. fn += `.${i}`;
  106. let tn = fileName + '.' + (i + 1);
  107. let exists = await fs.access(tn).then(() => true).catch(() => false);
  108. if (exists) {
  109. if (i >= LOG_ROTATE_FILE_DEPTH - 1) {
  110. await fs.unlink(tn);
  111. } else {
  112. await this.rotateFile(fileName, i + 1);
  113. }
  114. }
  115. await fs.rename(fn, tn);
  116. }
  117. async doFileRotationIfNeeded() {
  118. this.rcid = 0;
  119. let stat = await fs.fstat(this.fd);
  120. if (stat.size > LOG_ROTATE_FILE_LENGTH) {
  121. await fs.close(this.fd);
  122. await this.rotateFile(this.fileName, 0);
  123. this.fd = await fs.open(this.fileName, "a");
  124. }
  125. }
  126. async flushImpl(data) {
  127. if (this.closed)
  128. return;
  129. if (!this.rcid) {
  130. await this.doFileRotationIfNeeded();
  131. this.rcid = setTimeout(() => {
  132. this.rcid = 0;
  133. }, LOG_ROTATE_FILE_CHECK_INTERVAL);
  134. }
  135. if (this.fd)
  136. await fs.write(this.fd, Buffer.from(data.join('')));
  137. }
  138. }
  139. class ConsoleLog extends BaseLog {
  140. async flushImpl(data) {
  141. process.stdout.write(data.join(''));
  142. }
  143. }
  144. //------------------------------------------------------------------
  145. const factory = {
  146. ConsoleLog,
  147. FileLog,
  148. };
  149. class Logger {
  150. constructor(params = null) {
  151. this.handlers = [];
  152. if (params) {
  153. params.forEach((logParams) => {
  154. let className = logParams.log;
  155. let loggerClass = factory[className];
  156. this.handlers.push(new loggerClass(logParams));
  157. });
  158. }
  159. this.closed = false;
  160. ayncExit.onSignal((signal, err) => {
  161. this.log(LM_FATAL, `Signal "${signal}" received, error: "${(err.stack ? err.stack : err)}", exiting...`);
  162. });
  163. ayncExit.addAfter(this.close.bind(this));
  164. }
  165. formatDate(date) {
  166. return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ` +
  167. `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}.` +
  168. `${date.getMilliseconds().toString().padStart(3, '0')}`;
  169. }
  170. prepareMessage(msgType, message) {
  171. return this.formatDate(new Date()) + ` ${msgTypeToStr[msgType]}: ${message}\n`;
  172. }
  173. log(msgType, message) {
  174. if (message == null) {
  175. message = msgType;
  176. msgType = LM_INFO;
  177. }
  178. const mes = this.prepareMessage(msgType, message);
  179. if (!this.closed) {
  180. for (let i = 0; i < this.handlers.length; i++)
  181. this.handlers[i].log(msgType, mes);
  182. } else {
  183. console.log(mes);
  184. }
  185. return mes;
  186. }
  187. async close() {
  188. for (let i = 0; i < this.handlers.length; i++)
  189. await this.handlers[i].close();
  190. this.closed = true;
  191. }
  192. }
  193. module.exports = Logger;