Commits

Gregory Petukhov committed 4e31c83

Color logs

  • Participants
  • Parent commits 4f37c6d

Comments (0)

Files changed (1)

File tools/logs.py

 import logging
+import copy
+
+COLOR_RED = '\x1b[31m'
+COLOR_YELLOW = '\x1b[33m'
+COLOR_NORMAL = '\x1b[0m'
+
+class ColorStreamHandler(logging.StreamHandler):
+    def emit(self, record):
+        # Need to make a actual copy of the record 
+        # to prevent altering the message for other loggers
+        myrecord = copy.copy(record)
+        levelno = myrecord.levelno
+        if( levelno >= 50 ): # CRITICAL / FATAL
+            color = COLOR_YELLOW # red
+        elif( levelno >= 40 ): # ERROR
+            color = COLOR_YELLOW # red
+        elif( levelno >= 30 ): # WARNING
+            color = COLOR_YELLOW # yellow
+        #elif( levelno >= 20 ): # INFO
+            #color = '\x1b[32m' # green
+        #elif( levelno >= 10 ): # DEBUG
+            #color = '\x1b[35m' # pink
+        else: # NOTSET and anything else
+            color = COLOR_NORMAL # normal
+        myrecord.msg = color + str(myrecord.msg) + COLOR_NORMAL  # normal
+        logging.StreamHandler.emit(self, myrecord)
+
 
 def setup_logging(prefix=None, history=True, log_dir='var/log'):
     logger = logging.getLogger()
         logger.removeHandler(handler)
     logger.setLevel(logging.DEBUG)
 
-    handler = logging.StreamHandler()
+    handler = ColorStreamHandler()
     handler.setFormatter(logging.Formatter('%(threadName)s %(message)s'))
     logger.addHandler(handler)