From 8a3c4025d3e5f594c4ebed34c700f1bf596b9d79 Mon Sep 17 00:00:00 2001 From: haydensun Date: Fri, 15 May 2020 00:09:09 +0800 Subject: [PATCH] Add logger for MAmotif --- mamotif/logging.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 mamotif/logging.py diff --git a/mamotif/logging.py b/mamotif/logging.py new file mode 100644 index 0000000..06de709 --- /dev/null +++ b/mamotif/logging.py @@ -0,0 +1,42 @@ +""" +mamotif.logging +----------------- + +Logging configurations for MAmotif. +""" + +import logging +import sys + +# Initialize the default logger with a NullHandler +logger = logging.getLogger('mamotif') +logger.addHandler(logging.NullHandler()) + + +class CleanFormatter(logging.Formatter): + """Clean logging formatter, omit the level label for `logging.INFO`.""" + + def format(self, record): + if record.levelno != logging.INFO: + record.msg = f"{record.levelname}: {record.msg}" + return super().format(record) + + +def setup_logger(verbose=False): + """Setup logger with a stderr stream handler.""" + logger.setLevel(logging.DEBUG) + # clear all handlers + for handler in logger.handlers: + logger.removeHandler(handler) + + sh = logging.StreamHandler(stream=sys.stderr) + if verbose: + sh.setLevel(logging.DEBUG) + formatter = logging.Formatter( + "%(asctime)s %(name)-28s %(lineno)-4d %(levelname)-8s %(message)s", + datefmt="%Y-%m-%d %H:%M") + else: + sh.setLevel(logging.INFO) + formatter = CleanFormatter() + sh.setFormatter(formatter) + logger.addHandler(sh)