formatter.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import os
  5. import texttable
  6. from compose.cli import colors
  7. def get_tty_width():
  8. tty_size = os.popen('stty size 2> /dev/null', 'r').read().split()
  9. if len(tty_size) != 2:
  10. return 0
  11. _, width = tty_size
  12. return int(width)
  13. class Formatter(object):
  14. """Format tabular data for printing."""
  15. def table(self, headers, rows):
  16. table = texttable.Texttable(max_width=get_tty_width())
  17. table.set_cols_dtype(['t' for h in headers])
  18. table.add_rows([headers] + rows)
  19. table.set_deco(table.HEADER)
  20. table.set_chars(['-', '|', '+', '-'])
  21. return table.draw()
  22. class ConsoleWarningFormatter(logging.Formatter):
  23. """A logging.Formatter which prints WARNING and ERROR messages with
  24. a prefix of the log level colored appropriate for the log level.
  25. """
  26. def get_level_message(self, record):
  27. separator = ': '
  28. if record.levelno == logging.WARNING:
  29. return colors.yellow(record.levelname) + separator
  30. if record.levelno == logging.ERROR:
  31. return colors.red(record.levelname) + separator
  32. return ''
  33. def format(self, record):
  34. message = super(ConsoleWarningFormatter, self).format(record)
  35. return self.get_level_message(record) + message