bmaptool: prefix debug messages with time-stamp
authorArtem Bityutskiy <artem.bityutskiy@intel.com>
Tue, 24 Sep 2013 08:40:12 +0000 (11:40 +0300)
committerArtem Bityutskiy <artem.bityutskiy@intel.com>
Mon, 30 Sep 2013 07:10:03 +0000 (10:10 +0300)
This patch makes the debug messages to be prefixed with time-stamp, as well as
the module name and line number. The time-stamp is highlighted with green
color.

This patch introduces a custom formatter class in order to be able to format
debug and other loglevls differently.

Change-Id: I8ed40957ced9cdcd20ee7e94a6c92ce62671a5cc
Signed-off-by: Artem Bityutskiy <artem.bityutskiy@intel.com>
bmaptool

index 06d57c845fc19ea2590aa931d27161cf960f2e2e..3d30bc30b81e6aaf3e0ae566ca8db7350af5ce76 100755 (executable)
--- a/bmaptool
+++ b/bmaptool
@@ -640,8 +640,38 @@ def setup_logger(loglevel):
     # Esc-sequences for coloured output
     esc_red = '\033[91m'    # pylint: disable=W1401
     esc_yellow = '\033[93m' # pylint: disable=W1401
+    esc_green = '\033[92m' # pylint: disable=W1401
     esc_end = '\033[0m'     # pylint: disable=W1401
 
+    class MyFormatter(logging.Formatter):
+        """
+        A custom formatter for logging messages. The reason we have it is to
+        have different format for different debug levels.
+        """
+
+        def __init__(self, fmt=None, datefmt=None):
+            """The constructor."""
+            logging.Formatter.__init__(self, fmt, datefmt)
+
+            self._orig_fmt = self._fmt
+            # Prefix with green-colored time-stamp, as well as with module name
+            # and line number
+            self._dbg_fmt = "[" + esc_green + "%(asctime)s" + esc_end + \
+                            "] [%(module)s,%(lineno)d] " + self._fmt
+
+        def format(self, record):
+            """
+            The formatter which which simply prefixes all debugging messages
+            with a time-stamp.
+            """
+
+            if record.levelno == logging.DEBUG:
+                self._fmt = self._dbg_fmt
+
+            result = logging.Formatter.format(self, record)
+            self._fmt = self._orig_fmt
+            return result
+
     # Change log level names to something less nicer than the default
     # all-capital 'INFO' etc.
     logging.addLevelName(logging.ERROR, esc_red + "ERROR" + esc_end)
@@ -651,7 +681,7 @@ def setup_logger(loglevel):
 
     log = logging.getLogger('bmap-logger')
     log.setLevel(loglevel)
-    formatter = logging.Formatter("bmaptool: %(levelname)s: %(message)s")
+    formatter = MyFormatter("bmaptool: %(levelname)s: %(message)s", "%H:%M:%S")
     where = logging.StreamHandler(sys.stderr)
     where.setFormatter(formatter)
     log.addHandler(where)