utils.py 1.9 KB

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