From: Alfredo Deza Date: Wed, 29 Jan 2014 21:24:43 +0000 (-0500) Subject: make sure we can support color for logging X-Git-Tag: v1.3.5~6^2 X-Git-Url: http://git-server-git.apps.pok.os.sepia.ceph.com/?a=commitdiff_plain;h=refs%2Fpull%2F157%2Fhead;p=ceph-deploy.git make sure we can support color for logging Signed-off-by: Alfredo Deza --- diff --git a/ceph_deploy/util/log.py b/ceph_deploy/util/log.py index 3b4e8ad..2a236be 100644 --- a/ceph_deploy/util/log.py +++ b/ceph_deploy/util/log.py @@ -1,4 +1,5 @@ import logging +import sys BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) @@ -18,6 +19,19 @@ BASE_COLOR_FORMAT = "[$BOLD%(name)s$RESET][%(color_levelname)-17s] %(message)s" BASE_FORMAT = "%(asctime)s [%(name)s][%(levelname)-6s] %(message)s" +def supports_color(): + """ + Returns True if the running system's terminal supports color, and False + otherwise. + """ + unsupported_platform = (sys.platform in ('win32', 'Pocket PC')) + # isatty is not always implemented, #6223. + is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() + if unsupported_platform or not is_a_tty: + return False + return True + + def color_message(message): message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) return message @@ -36,9 +50,11 @@ class ColoredFormatter(logging.Formatter): def format(self, record): levelname = record.levelname truncated_level = record.levelname[:6] - if levelname in COLORS: + if levelname in COLORS and supports_color(): levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + truncated_level + RESET_SEQ record.color_levelname = levelname_color + else: + record.color_levelname = levelname return logging.Formatter.format(self, record)