handlers.py 1.2 KB

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