Only print extra log details in DEBUG mode 90/12390/8
authorThanh Ha <thanh.ha@linuxfoundation.org>
Sat, 25 Aug 2018 01:04:13 +0000 (21:04 -0400)
committerThanh Ha <thanh.ha@linuxfoundation.org>
Mon, 27 Aug 2018 22:29:09 +0000 (18:29 -0400)
This allow us to change all our print statements to log.info() and
have it still print sanely like a CLI application. Then when DEBUG
mode is enabled it will print the extra details to let us
troubleshoot. ERROR and CRITICAL logs will prefix with "ERROR: "
for example.

Change-Id: Ic35222ee654306e686052c209b641f9e49d38144
Signed-off-by: Thanh Ha <thanh.ha@linuxfoundation.org>
lftools/__init__.py
releasenotes/notes/logger-c53984ef7b1da53f.yaml [new file with mode: 0644]

index f3f83ed..eea82a2 100644 (file)
@@ -16,10 +16,28 @@ __author__ = 'Thanh Ha'
 __summary__ = 'Linux Foundation Release Engineering Tools'
 
 import logging
-import logging.config
+import sys
 
-formatter = logging.Formatter('(%(levelname)s) %(name)s: %(message)s')
-console_handler = logging.StreamHandler()
-console_handler.setFormatter(formatter)
+
+class LogFormatter(logging.Formatter):
+    """Custom log formatter."""
+
+    default_fmt = logging.Formatter('%(levelname)s: %(message)s')
+    debug_fmt = logging.Formatter(
+        '%(levelname)s: %(name)s:%(lineno)d: %(message)s')
+    info_fmt = logging.Formatter('%(message)s')
+
+    def format(self, record):
+        """Format log messages depending on log level."""
+        if record.levelno == logging.INFO:
+            return self.info_fmt.format(record)
+        if record.levelno == logging.DEBUG:
+            return self.debug_fmt.format(record)
+        else:
+            return self.default_fmt.format(record)
+
+
+console_handler = logging.StreamHandler(sys.stdout)
+console_handler.setFormatter(LogFormatter())
 logging.getLogger("").setLevel(logging.INFO)
 logging.getLogger("").addHandler(console_handler)
diff --git a/releasenotes/notes/logger-c53984ef7b1da53f.yaml b/releasenotes/notes/logger-c53984ef7b1da53f.yaml
new file mode 100644 (file)
index 0000000..86f3e20
--- /dev/null
@@ -0,0 +1,6 @@
+---
+other:
+  - |
+    Enhance logger subsystem to work better as a CLI program. This is a first
+    step to migrating all lftools subsystems to use the logger instead of print
+    statements everywhere.