From: Thanh Ha Date: Sat, 25 Aug 2018 01:04:13 +0000 (-0400) Subject: Only print extra log details in DEBUG mode X-Git-Tag: v0.17.0~5 X-Git-Url: https://gerrit.linuxfoundation.org/infra/gitweb?a=commitdiff_plain;h=4edf459161faeaebe1614ff16f18101f0785adc6;p=releng%2Flftools.git Only print extra log details in DEBUG mode 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 --- diff --git a/lftools/__init__.py b/lftools/__init__.py index f3f83ed8..eea82a26 100644 --- a/lftools/__init__.py +++ b/lftools/__init__.py @@ -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 index 00000000..86f3e207 --- /dev/null +++ b/releasenotes/notes/logger-c53984ef7b1da53f.yaml @@ -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.