tcp-server.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const debug = require('debug')('log4js:tcp-server');
  2. const net = require('net');
  3. const clustering = require('../clustering');
  4. const LoggingEvent = require('../LoggingEvent');
  5. const DELIMITER = '__LOG4JS__';
  6. exports.configure = (config) => {
  7. debug('configure called with ', config);
  8. // dummy shutdown if we're not master
  9. let shutdown = (cb) => { cb(); };
  10. clustering.onlyOnMaster(() => {
  11. const server = net.createServer((socket) => {
  12. let dataSoFar = '';
  13. const send = (data) => {
  14. if (data) {
  15. dataSoFar += data;
  16. if (dataSoFar.indexOf(DELIMITER)) {
  17. const events = dataSoFar.split(DELIMITER);
  18. if (!dataSoFar.endsWith(DELIMITER)) {
  19. dataSoFar = events.pop();
  20. } else {
  21. dataSoFar = '';
  22. }
  23. events.filter(e => e.length).forEach((e) => {
  24. clustering.send(LoggingEvent.deserialise(e));
  25. });
  26. }
  27. }
  28. };
  29. socket.setEncoding('utf8');
  30. socket.on('data', send);
  31. socket.on('end', send);
  32. });
  33. server.listen(config.port || 5000, config.host || 'localhost', () => {
  34. debug(`listening on ${config.host || 'localhost'}:${config.port || 5000}`);
  35. server.unref();
  36. });
  37. shutdown = (cb) => {
  38. debug('shutdown called.');
  39. server.close(cb);
  40. };
  41. });
  42. return {
  43. shutdown
  44. };
  45. };