Logger.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. try {
  42. await this.flushImpl(this.data);
  43. } catch (e) {
  44. console.error(`Logger error: ${e}`);
  45. ayncExit.exit(1);
  46. }
  47. this.flushing = false;
  48. }
  49. log(msgType, message) {
  50. if (this.closed)
  51. return;
  52. if (!this.exclude.has(msgType)) {
  53. this.outputBuffer.push(message);
  54. this.outputBufferLength += message.length;
  55. if (this.outputBufferLength >= LOG_CACHE_BUFFER_SIZE && !this.flushing) {
  56. this.flush();
  57. }
  58. if (!this.iid) {
  59. this.iid = setInterval(() => {
  60. if (!this.flushing) {
  61. clearInterval(this.iid);
  62. this.iid = 0;
  63. this.flush();
  64. }
  65. }, LOG_BUFFER_FLUSH_INTERVAL);
  66. }
  67. }
  68. }
  69. async close() {
  70. if (this.closed)
  71. return;
  72. if (this.iid)
  73. clearInterval(this.iid);
  74. try {
  75. while (this.outputBufferLength) {
  76. await this.flush();
  77. await sleep(1);
  78. }
  79. } catch(e) {
  80. console.log(e);
  81. ayncExit.exit(1);
  82. }
  83. this.outputBufferLength = 0;
  84. this.outputBuffer = [];
  85. this.closed = true;
  86. }
  87. }
  88. class FileLog extends BaseLog {
  89. constructor(params) {
  90. super(params);
  91. this.fileName = params.fileName;
  92. this.fd = fs.openSync(this.fileName, 'a');
  93. this.rcid = 0;
  94. }
  95. async close() {
  96. if (this.closed)
  97. return;
  98. await super.close();
  99. if (this.fd) {
  100. while (this.flushing)
  101. await sleep(1);
  102. await fs.close(this.fd);
  103. this.fd = null;
  104. }
  105. if (this.rcid)
  106. clearTimeout(this.rcid);
  107. }
  108. async rotateFile(fileName, i) {
  109. let fn = fileName;
  110. if (i > 0)
  111. fn += `.${i}`;
  112. let tn = fileName + '.' + (i + 1);
  113. let exists = await fs.access(tn).then(() => true).catch(() => false);
  114. if (exists) {
  115. if (i >= LOG_ROTATE_FILE_DEPTH - 1) {
  116. await fs.unlink(tn);
  117. } else {
  118. await this.rotateFile(fileName, i + 1);
  119. }
  120. }
  121. await fs.rename(fn, tn);
  122. }
  123. async doFileRotationIfNeeded() {
  124. this.rcid = 0;
  125. let stat = await fs.fstat(this.fd);
  126. if (stat.size > LOG_ROTATE_FILE_LENGTH) {
  127. await fs.close(this.fd);
  128. await this.rotateFile(this.fileName, 0);
  129. this.fd = await fs.open(this.fileName, "a");
  130. }
  131. }
  132. async flushImpl(data) {
  133. if (this.closed)
  134. return;
  135. this.flushing = true;
  136. try {
  137. if (!this.rcid) {
  138. await this.doFileRotationIfNeeded();
  139. this.rcid = setTimeout(() => {
  140. this.rcid = 0;
  141. }, LOG_ROTATE_FILE_CHECK_INTERVAL);
  142. }
  143. if (this.fd) {
  144. await fs.write(this.fd, Buffer.from(data.join('')));
  145. }
  146. } finally {
  147. this.flushing = false;
  148. }
  149. }
  150. }
  151. class ConsoleLog extends BaseLog {
  152. async flushImpl(data) {
  153. process.stdout.write(data.join(''));
  154. }
  155. }
  156. //------------------------------------------------------------------
  157. const factory = {
  158. ConsoleLog,
  159. FileLog,
  160. };
  161. class Logger {
  162. constructor(params = null) {
  163. this.handlers = [];
  164. if (params) {
  165. params.forEach((logParams) => {
  166. let className = logParams.log;
  167. let loggerClass = factory[className];
  168. this.handlers.push(new loggerClass(logParams));
  169. });
  170. }
  171. this.closed = false;
  172. ayncExit.onSignal((signal, err) => {
  173. this.log(LM_FATAL, `Signal "${signal}" received, error: "${(err.stack ? err.stack : err)}", exiting...`);
  174. });
  175. ayncExit.addAfter(this.close.bind(this));
  176. }
  177. formatDate(date) {
  178. return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ` +
  179. `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}.` +
  180. `${date.getMilliseconds().toString().padStart(3, '0')}`;
  181. }
  182. prepareMessage(msgType, message) {
  183. return this.formatDate(new Date()) + ` ${msgTypeToStr[msgType]}: ${message}\n`;
  184. }
  185. log(msgType, message) {
  186. if (message == null) {
  187. message = msgType;
  188. msgType = LM_INFO;
  189. }
  190. const mes = this.prepareMessage(msgType, message);
  191. if (!this.closed) {
  192. for (let i = 0; i < this.handlers.length; i++)
  193. this.handlers[i].log(msgType, mes);
  194. } else {
  195. console.log(mes);
  196. }
  197. return mes;
  198. }
  199. async close() {
  200. for (let i = 0; i < this.handlers.length; i++)
  201. await this.handlers[i].close();
  202. this.closed = true;
  203. }
  204. }
  205. module.exports = Logger;