log_printer.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. # Attach to container before log printer starts running
  26. line_generator = split_buffer(self._attach(container), '\n')
  27. return (prefix + line for line in line_generator)
  28. def _attach(self, container):
  29. params = {
  30. 'stdout': True,
  31. 'stderr': True,
  32. 'stream': True,
  33. }
  34. params.update(self.attach_params)
  35. params = dict((name, 1 if value else 0) for (name, value) in list(params.items()))
  36. return container.attach(**params)
  37. def split_buffer(reader, separator):
  38. """
  39. Given a generator which yields strings and a separator string,
  40. joins all input, splits on the separator and yields each chunk.
  41. Requires that each input string is decodable as UTF-8.
  42. """
  43. buffered = ''
  44. for data in reader:
  45. lines = (buffered + data.decode('utf-8')).split(separator)
  46. for line in lines[:-1]:
  47. yield line + separator
  48. if len(lines) > 1:
  49. buffered = lines[-1]
  50. if len(buffered) > 0:
  51. yield buffered