log_printer.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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, STOP
  6. from . import colors
  7. from .utils import split_buffer
  8. class LogPrinter(object):
  9. def __init__(self, containers, attach_params=None, output=sys.stdout):
  10. self.containers = containers
  11. self.attach_params = attach_params or {}
  12. self.prefix_width = self._calculate_prefix_width(containers)
  13. self.generators = self._make_log_generators()
  14. self.output = output
  15. def run(self):
  16. mux = Multiplexer(self.generators)
  17. for line in mux.loop():
  18. self.output.write(line)
  19. def _calculate_prefix_width(self, containers):
  20. """
  21. Calculate the maximum width of container names so we can make the log
  22. prefixes line up like so:
  23. db_1 | Listening
  24. web_1 | Listening
  25. """
  26. prefix_width = 0
  27. for container in containers:
  28. prefix_width = max(prefix_width, len(container.name_without_project))
  29. return prefix_width
  30. def _make_log_generators(self):
  31. color_fns = cycle(colors.rainbow())
  32. generators = []
  33. for container in self.containers:
  34. color_fn = color_fns.next()
  35. generators.append(self._make_log_generator(container, color_fn))
  36. return generators
  37. def _make_log_generator(self, container, color_fn):
  38. prefix = color_fn(self._generate_prefix(container)).encode('utf-8')
  39. # Attach to container before log printer starts running
  40. line_generator = split_buffer(self._attach(container), '\n')
  41. for line in line_generator:
  42. yield prefix + line
  43. exit_code = container.wait()
  44. yield color_fn("%s exited with code %s\n" % (container.name, exit_code))
  45. yield STOP
  46. def _generate_prefix(self, container):
  47. """
  48. Generate the prefix for a log line without colour
  49. """
  50. name = container.name_without_project
  51. padding = ' ' * (self.prefix_width - len(name))
  52. return ''.join([name, padding, ' | '])
  53. def _attach(self, container):
  54. params = {
  55. 'stdout': True,
  56. 'stderr': True,
  57. 'stream': True,
  58. }
  59. params.update(self.attach_params)
  60. params = dict((name, 1 if value else 0) for (name, value) in list(params.items()))
  61. return container.attach(**params)