utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from logging.handlers import BufferingHandler
  2. from gixy.formatters.base import BaseFormatter
  3. class LogHandler(BufferingHandler):
  4. def __init__(self, matcher):
  5. # BufferingHandler takes a "capacity" argument
  6. # so as to know when to flush. As we're overriding
  7. # shouldFlush anyway, we can set a capacity of zero.
  8. # You can call flush() manually to clear out the
  9. # buffer.
  10. super(LogHandler, self).__init__(0)
  11. self.matcher = matcher
  12. def shouldFlush(self, **kwargs):
  13. return False
  14. def emit(self, record):
  15. self.buffer.append(record.__dict__)
  16. def matches(self, **kwargs):
  17. """
  18. Look for a saved dict whose keys/values match the supplied arguments.
  19. """
  20. result = False
  21. for d in self.buffer:
  22. if self.matcher.matches(d, **kwargs):
  23. result = True
  24. break
  25. return result
  26. class Matcher(object):
  27. _partial_matches = ('msg', 'message')
  28. def matches(self, d, **kwargs):
  29. """
  30. Try to match a single dict with the supplied arguments.
  31. Keys whose values are strings and which are in self._partial_matches
  32. will be checked for partial (i.e. substring) matches. You can extend
  33. this scheme to (for example) do regular expression matching, etc.
  34. """
  35. result = True
  36. for k in kwargs:
  37. v = kwargs[k]
  38. dv = d.get(k)
  39. if not self.match_value(k, dv, v):
  40. result = False
  41. break
  42. return result
  43. def match_value(self, k, dv, v):
  44. """
  45. Try to match a single stored value (dv) with a supplied value (v).
  46. """
  47. if type(v) != type(dv):
  48. result = False
  49. elif type(dv) is not str or k not in self._partial_matches:
  50. result = (v == dv)
  51. else:
  52. result = dv.find(v) >= 0
  53. return result