file_buffer.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. 'use strict';
  2. const depd = require('depd')('egg-logger');
  3. const FileTransport = require('./file');
  4. const utils = require('../utils');
  5. /**
  6. * extends from {@link FileTransport}
  7. * save log in memory and flush to log file at intervals
  8. */
  9. class FileBufferTransport extends FileTransport {
  10. /**
  11. * @class
  12. * @param {Object} options
  13. * - {String} file - log file path
  14. * - {Number} [flushInterval = 1000] - interval for flush to file
  15. * - {Number} [maxBufferLength = 1000] - max buffer queue length
  16. * - {String} [level = INFO] - log level
  17. */
  18. constructor(options) {
  19. super(options);
  20. this._bufSize = 0;
  21. this._buf = [];
  22. this._timer = this._createInterval();
  23. }
  24. get defaults() {
  25. return utils.assign(super.defaults, {
  26. flushInterval: 1000,
  27. maxBufferLength: 1000,
  28. });
  29. }
  30. /**
  31. * close stream and interval
  32. */
  33. close() {
  34. this._closeInterval();
  35. super.close();
  36. }
  37. /**
  38. * @deprecated
  39. */
  40. end() {
  41. depd('transport.end() is deprecated, use transport.close()');
  42. this.close();
  43. }
  44. /**
  45. * flush log into file
  46. */
  47. flush() {
  48. if (this._buf.length > 0 && this.writable) {
  49. if (this.options.encoding === 'utf8') {
  50. this._stream.write(this._buf.join(''));
  51. } else {
  52. this._stream.write(Buffer.concat(this._buf, this._bufSize));
  53. }
  54. this._buf = [];
  55. this._bufSize = 0;
  56. }
  57. }
  58. /**
  59. * override, flush before close stream
  60. * @private
  61. */
  62. _closeStream() {
  63. // FileTransport 在初始化时会 reload,这时 _buf 还未初始化
  64. if (this._buf && this._buf.length > 0) {
  65. this.flush();
  66. }
  67. super._closeStream();
  68. }
  69. /**
  70. * override, save in memory temporary
  71. * @param {Buffer} buf - log buffer
  72. * @private
  73. */
  74. _write(buf) {
  75. this._bufSize += buf.length;
  76. this._buf.push(buf);
  77. if (this._buf.length > this.options.maxBufferLength) {
  78. this.flush();
  79. }
  80. }
  81. /**
  82. * create interval to flush log into file
  83. * @return {Interval} 定时器
  84. * @private
  85. */
  86. _createInterval() {
  87. return setInterval(() => this.flush(), this.options.flushInterval);
  88. }
  89. /**
  90. * close interval
  91. * @private
  92. */
  93. _closeInterval() {
  94. if (this._timer) {
  95. clearInterval(this._timer);
  96. this._timer = null;
  97. }
  98. }
  99. }
  100. module.exports = FileBufferTransport;