handlers.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. import stomp
  3. logger = logging.getLogger(__name__)
  4. class StompHandler(logging.Handler):
  5. """
  6. Send messages to a remote queue broker using the STOMP protocol.
  7. This module is named and configured separately from
  8. standard logging for clarity about its scope: while logging has an
  9. informational purpose, this module has a functional one.
  10. """
  11. def __init__(self, conf):
  12. self.conf = conf
  13. if self.conf['protocol'] == '11':
  14. conn_cls = stomp.Connection11
  15. elif self.conf['protocol'] == '12':
  16. conn_cls = stomp.Connection12
  17. else:
  18. conn_cls = stomp.Connection10
  19. self.conn = conn_cls([(self.conf['host'], self.conf['port'])])
  20. self.conn.start()
  21. try:
  22. self.conn.connect(
  23. username=self.conf['username'],
  24. passcode=self.conf['password'],
  25. wait=True
  26. )
  27. except stomp.exception.ConnectFailedException:
  28. logger.warning(
  29. 'Could not connect to the STOMP server. Your messages '
  30. 'will be ditched.')
  31. return super().__init__()
  32. def __del_(self):
  33. """Disconnect the client."""
  34. if self.conn.is_connected():
  35. self.conn.disconnect()
  36. def emit(self, record):
  37. """Send the message to the destination endpoint."""
  38. if self.conn.is_connected():
  39. self.conn.send(destination=self.conf['destination'],
  40. body=bytes(self.format(record), 'utf-8'))
  41. else:
  42. logger.warning('STOMP server not connected. Message dropped.')