Create a logger with color.
()
| 88 | |
| 89 | |
| 90 | def __create_logger(): |
| 91 | """Create a logger with color.""" |
| 92 | # The background is set with 40 plus the number of the color, and the foreground with 30 |
| 93 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) |
| 94 | |
| 95 | # These are the sequences need to get colored ouput |
| 96 | RESET_SEQ = "\033[0m" |
| 97 | COLOR_SEQ = "\033[1;%dm" |
| 98 | BOLD_SEQ = "\033[1m" |
| 99 | |
| 100 | COLORS = { |
| 101 | "WARNING": YELLOW, |
| 102 | "INFO": GREEN, |
| 103 | "DEBUG": BLUE, |
| 104 | "CRITICAL": YELLOW, |
| 105 | "ERROR": RED, |
| 106 | } |
| 107 | |
| 108 | class ColoredFormatter(logging.Formatter): |
| 109 | def __init__(self, msg, use_color=False): |
| 110 | logging.Formatter.__init__(self, msg) |
| 111 | self.use_color = use_color |
| 112 | |
| 113 | def format(self, record): |
| 114 | levelname = record.levelname |
| 115 | if self.use_color and levelname in COLORS: |
| 116 | levelname_color = ( |
| 117 | COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ |
| 118 | ) |
| 119 | record.levelname = levelname_color |
| 120 | return logging.Formatter.format(self, record) |
| 121 | |
| 122 | class ColoredLogger(logging.Logger): |
| 123 | FORMAT = "{}%(asctime)s{} %(levelname)19s %(message)s".format( |
| 124 | BOLD_SEQ, RESET_SEQ |
| 125 | ) |
| 126 | |
| 127 | def __init__(self, name): |
| 128 | logging.Logger.__init__(self, name, logging.DEBUG) |
| 129 | color_formatter = ColoredFormatter( |
| 130 | self.FORMAT, use_color=sys.stdout.isatty() and sys.stderr.isatty() |
| 131 | ) |
| 132 | console = logging.StreamHandler() |
| 133 | console.setFormatter(color_formatter) |
| 134 | self.addHandler(console) |
| 135 | return |
| 136 | |
| 137 | logging.setLoggerClass(ColoredLogger) |
| 138 | logger = logging.getLogger("tao_ci") |
| 139 | logger.setLevel(logging.INFO) |
| 140 | return logger |
| 141 | |
| 142 | |
| 143 | logger = __create_logger() |