handlers.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. try:
  21. self.conn.connect(
  22. username=self.conf['username'],
  23. passcode=self.conf['password'],
  24. wait=True
  25. )
  26. except stomp.exception.ConnectFailedException:
  27. logger.warning(
  28. 'Could not connect to the STOMP server. Your messages '
  29. 'will be ditched.')
  30. return super().__init__()
  31. def __del_(self):
  32. """Disconnect the client."""
  33. if self.conn.is_connected():
  34. self.conn.disconnect()
  35. def emit(self, record):
  36. """Send the message to the destination endpoint."""
  37. if self.conn.is_connected():
  38. self.conn.send(destination=self.conf['destination'],
  39. body=bytes(self.format(record), 'utf-8'))
  40. else:
  41. logger.warning('STOMP server not connected. Message dropped.')