__init__.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python3
  2. # encoding: utf8
  3. import logging
  4. class ColoredFormatter(logging.Formatter):
  5. FG_BLACK = 30
  6. FG_RED = 31
  7. FG_GREEN = 32
  8. FG_YELLOW = 33
  9. FG_BLUE = 34
  10. FG_MAGENTA = 35
  11. FG_CYAN = 36
  12. FG_WHITE = 37
  13. BG_BLACK = 40
  14. BG_RED = 41
  15. BG_GREEN = 42
  16. BG_YELLOW = 43
  17. BG_BLUE = 44
  18. BG_MAGENTA = 45
  19. BG_CYAN = 46
  20. BG_WHITE = 47
  21. BLACK = FG_BLACK
  22. RED = FG_RED
  23. GREEN = FG_GREEN
  24. YELLOW = FG_YELLOW
  25. BLUE = FG_BLUE
  26. MAGENTA = FG_MAGENTA
  27. CYAN = FG_CYAN
  28. WHITE = FG_WHITE
  29. # These are the sequences need to get colored ouput
  30. RESET_SEQ = "\033[0m"
  31. COLOR_SEQ = "\033[{:d}m"
  32. BOLD_SEQ = "\033[1m"
  33. # -------------------------------------------------------------------------
  34. def __init__( self,
  35. fmt=None,
  36. datefmt=None,
  37. style='%',
  38. colors={ 'WARNING' : YELLOW,
  39. 'DEBUG' : BLUE,
  40. 'CRITICAL': BG_RED,
  41. 'ERROR' : RED, } ):
  42. super(ColoredFormatter, self).__init__(fmt, datefmt, style)
  43. self.colors = colors
  44. # -------------------------------------------------------------------------
  45. def format(self, record):
  46. levelname = record.levelname
  47. if levelname in self.colors:
  48. return ( self.COLOR_SEQ.format(self.colors[levelname]) \
  49. + super(ColoredFormatter, self).format(record) \
  50. + self.RESET_SEQ )
  51. return super(ColoredFormatter, self).format(record) \
  52. # =============================================================================
  53. if __name__ == '__main__':
  54. log = logging.getLogger("test")
  55. log.setLevel(logging.DEBUG)
  56. log_handler= logging.StreamHandler()
  57. log_formatter = ColoredFormatter("%(asctime)s: %(message)s")
  58. log_handler.setFormatter(log_formatter)
  59. log.addHandler(log_handler)
  60. log.debug("This is a debug log")
  61. log.info("This is an info log")
  62. log.warning("This is warning log")
  63. log.error("This is an error log")
  64. log.critical("This is critical log")