1
0

utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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
  54. class RawFormatter(BaseFormatter):
  55. def format_reports(self, reports, stats):
  56. return reports