handlers.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import logging
  2. from abc import ABCMeta, abstractmethod
  3. from flask import current_app
  4. from stompest.config import StompConfig
  5. from stompest.protocol import StompSpec
  6. from stompest.sync import Stomp
  7. class StompHandler(logging.Handler):
  8. '''
  9. Send messages to a remote queue broker using the STOMP protocol.
  10. This module is named and configured separately from
  11. standard logging for clarity about its scope: while logging has an
  12. informational purpose, this module has a functional one.
  13. '''
  14. def __init__(self, conf):
  15. self.conf = conf
  16. if self.conf['protocol'] == '11':
  17. protocol_v = StompSpec.VERSION_1_1
  18. elif self.conf['protocol'] == '12':
  19. protocol_v = StompSpec.VERSION_1_2
  20. else:
  21. protocol_v = StompSpec.VERSION_1_0
  22. client_config = StompConfig(
  23. 'tcp://{}:{}'.format(self.conf['host'], self.conf['port']),
  24. login=self.conf['username'],
  25. passcode=self.conf['password'],
  26. version=protocol_v
  27. )
  28. self.conn = Stomp(client_config)
  29. self.conn.connect()
  30. return super().__init__()
  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'))