stats_logger.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # pylint: disable=C,R,W
  2. import logging
  3. from colorama import Fore, Style
  4. class BaseStatsLogger(object):
  5. """Base class for logging realtime events"""
  6. def __init__(self, prefix='superset'):
  7. self.prefix = prefix
  8. def key(self, key):
  9. if self.prefix:
  10. return self.prefix + key
  11. return key
  12. def incr(self, key):
  13. """Increment a counter"""
  14. raise NotImplementedError()
  15. def decr(self, key):
  16. """Decrement a counter"""
  17. raise NotImplementedError()
  18. def timing(self, key, value):
  19. raise NotImplementedError()
  20. def gauge(self, key):
  21. """Setup a gauge"""
  22. raise NotImplementedError()
  23. class DummyStatsLogger(BaseStatsLogger):
  24. def incr(self, key):
  25. logging.debug(
  26. Fore.CYAN + '[stats_logger] (incr) ' + key + Style.RESET_ALL)
  27. def decr(self, key):
  28. logging.debug((
  29. Fore.CYAN + '[stats_logger] (decr) ' + key +
  30. Style.RESET_ALL))
  31. def timing(self, key, value):
  32. logging.debug((
  33. Fore.CYAN + '[stats_logger] (timing) {key} | {value} ' +
  34. Style.RESET_ALL).format(**locals()))
  35. def gauge(self, key, value):
  36. logging.debug((
  37. Fore.CYAN + '[stats_logger] (gauge) '
  38. '{key} | {value}' + Style.RESET_ALL).format(**locals()))
  39. try:
  40. from statsd import StatsClient
  41. class StatsdStatsLogger(BaseStatsLogger):
  42. def __init__(self, host, port, prefix='superset'):
  43. self.client = StatsClient(host=host, port=port, prefix=prefix)
  44. def incr(self, key):
  45. self.client.incr(key)
  46. def decr(self, key):
  47. self.client.decr(key)
  48. def timing(self, key, value):
  49. self.client.timing(key, value)
  50. def gauge(self, key):
  51. # pylint: disable=no-value-for-parameter
  52. self.client.gauge(key)
  53. except Exception as e:
  54. pass