From: Ben Darnell Date: Thu, 20 Apr 2017 01:38:57 +0000 (-0400) Subject: log: Fix color logging detection X-Git-Tag: v4.5.1~1^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F2019%2Fhead;p=thirdparty%2Ftornado.git log: Fix color logging detection The previous logic would fail whenever curses is missing (which is always true on windows, and is occasionally true on other platforms) and colorama is installed but not initialized in this process (this is a common occurrence for users of jupyter and ipython on windows). Fixes #2013 Fixes #2015 --- diff --git a/tornado/log.py b/tornado/log.py index 01519177a..654afc021 100644 --- a/tornado/log.py +++ b/tornado/log.py @@ -54,18 +54,21 @@ gen_log = logging.getLogger("tornado.general") def _stderr_supports_color(): - color = False - if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): - if curses: - try: + try: + if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): + if curses: curses.setupterm() if curses.tigetnum("colors") > 0: - color = True - except Exception: - pass - elif colorama: - color = True - return color + return True + elif colorama: + if sys.stderr is getattr(colorama.initialise, 'wrapped_stderr', + object()): + return True + except Exception: + # Very broad exception handling because it's always better to + # fall back to non-colored logs than to break at startup. + pass + return False def _safe_unicode(s): @@ -146,12 +149,12 @@ class LogFormatter(logging.Formatter): for levelno, code in colors.items(): self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), "ascii") self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii") - elif sys.stderr is getattr(colorama, 'wrapped_stderr', object()): + else: + # If curses is not present (currently we'll only get here for + # colorama on windows), assume hard-coded ANSI color codes. for levelno, code in colors.items(): self._colors[levelno] = '\033[2;3%dm' % code self._normal = '\033[0m' - else: - raise RuntimeError("No supported color terminal library") else: self._normal = ''