handlers.py 1.3 KB

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