]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
log: Fix color logging detection 2019/head
authorBen Darnell <ben@bendarnell.com>
Thu, 20 Apr 2017 01:38:57 +0000 (21:38 -0400)
committerBen Darnell <ben@bendarnell.com>
Thu, 20 Apr 2017 02:33:33 +0000 (22:33 -0400)
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

tornado/log.py

index 01519177aada3a630d07170c6d6aed7c14a4b715..654afc021e6e818b4d6900dfc2b23ba7c43f4de3 100644 (file)
@@ -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 = ''