tcp.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. const debug = require('debug')('log4js:tcp');
  3. const net = require('net');
  4. function appender(config) {
  5. let canWrite = false;
  6. const buffer = [];
  7. let socket;
  8. let shutdownAttempts = 3;
  9. function write(loggingEvent) {
  10. debug('Writing log event to socket');
  11. canWrite = socket.write(`${loggingEvent.serialise()}__LOG4JS__`, 'utf8');
  12. }
  13. function emptyBuffer() {
  14. let evt;
  15. debug('emptying buffer');
  16. /* eslint no-cond-assign:0 */
  17. while ((evt = buffer.shift())) {
  18. write(evt);
  19. }
  20. }
  21. function createSocket() {
  22. debug(`appender creating socket to ${config.host || 'localhost'}:${config.port || 5000}`);
  23. socket = net.createConnection(config.port || 5000, config.host || 'localhost');
  24. socket.on('connect', () => {
  25. debug('socket connected');
  26. emptyBuffer();
  27. canWrite = true;
  28. });
  29. socket.on('drain', () => {
  30. debug('drain event received, emptying buffer');
  31. canWrite = true;
  32. emptyBuffer();
  33. });
  34. socket.on('timeout', socket.end.bind(socket));
  35. // don't bother listening for 'error', 'close' gets called after that anyway
  36. socket.on('close', createSocket);
  37. }
  38. createSocket();
  39. function log(loggingEvent) {
  40. if (canWrite) {
  41. write(loggingEvent);
  42. } else {
  43. debug('buffering log event because it cannot write at the moment');
  44. buffer.push(loggingEvent);
  45. }
  46. }
  47. log.shutdown = function (cb) {
  48. debug('shutdown called');
  49. if (buffer.length && shutdownAttempts) {
  50. debug('buffer has items, waiting 100ms to empty');
  51. shutdownAttempts -= 1;
  52. setTimeout(() => {
  53. log.shutdown(cb);
  54. }, 100);
  55. } else {
  56. socket.removeAllListeners('close');
  57. socket.end(cb);
  58. }
  59. };
  60. return log;
  61. }
  62. function configure(config) {
  63. debug(`configure with config = ${config}`);
  64. return appender(config);
  65. }
  66. module.exports.configure = configure;