log_printer.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. import sys
  4. from itertools import cycle
  5. from .multiplexer import Multiplexer
  6. from . import colors
  7. class LogPrinter(object):
  8. def __init__(self, containers, attach_params=None):
  9. self.containers = containers
  10. self.attach_params = attach_params or {}
  11. self.generators = self._make_log_generators()
  12. def run(self):
  13. mux = Multiplexer(self.generators)
  14. for line in mux.loop():
  15. sys.stdout.write(line)
  16. def _make_log_generators(self):
  17. color_fns = cycle(colors.rainbow())
  18. generators = []
  19. for container in self.containers:
  20. color_fn = color_fns.next()
  21. generators.append(self._make_log_generator(container, color_fn))
  22. return generators
  23. def _make_log_generator(self, container, color_fn):
  24. prefix = color_fn(container.name + " | ")
  25. for line in split_buffer(self._attach(container), '\n'):
  26. yield prefix + line
  27. def _attach(self, container):
  28. params = {
  29. 'stdout': True,
  30. 'stderr': True,
  31. 'stream': True,
  32. }
  33. params.update(self.attach_params)
  34. params = dict((name, 1 if value else 0) for (name, value) in list(params.items()))
  35. return container.attach(**params)
  36. def split_buffer(reader, separator):
  37. """
  38. Given a generator which yields strings and a separator string,
  39. joins all input, splits on the separator and yields each chunk.
  40. Requires that each input string is decodable as UTF-8.
  41. """
  42. buffered = ''
  43. for data in reader:
  44. lines = (buffered + data.decode('utf-8')).split(separator)
  45. for line in lines[:-1]:
  46. yield line + separator
  47. if len(lines) > 1:
  48. buffered = lines[-1]
  49. if len(buffered) > 0:
  50. yield buffered