From 30d31c377499b59c5d878d8b381d1e635dcb8b36 Mon Sep 17 00:00:00 2001 From: Alfredo Deza Date: Wed, 29 Jan 2014 16:24:43 -0500 Subject: [PATCH] make sure we can support color for logging Signed-off-by: Alfredo Deza --- ceph_deploy/util/log.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) 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) -- 2.47.3