From 510483dd4f46ca75090ae75eadbbbb7089fbb4db Mon Sep 17 00:00:00 2001 From: Anthony Rebello Date: Thu, 16 Feb 2017 12:36:33 +0530 Subject: [PATCH] fixes #33, no-op logger when user silences logs when the user passes --quiet without specifying a --log-file, there is no need to ever process log statements. a no-op dummy object acts as a log. --- basescript/basescript.py | 14 ++++++++++---- basescript/utils.py | 9 +++++++++ setup.py | 2 +- 3 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 basescript/utils.py diff --git a/basescript/basescript.py b/basescript/basescript.py index 9005d9c..b656d1d 100644 --- a/basescript/basescript.py +++ b/basescript/basescript.py @@ -12,6 +12,7 @@ from .log import LevelLoggerFactory, BoundLevelLogger, StdlibStructlogHandler, StderrConsoleRenderer, Stream from .stats import Stats +from .utils import Dummy class BaseScript(object): DESC = 'Base script abstraction' @@ -133,6 +134,10 @@ def define_log_post_format_hooks(self): return [] def _configure_logger(self): + """ + configures a logger when required write to stderr or a file + """ + # NOTE not thread safe. Multiple BaseScripts cannot be instantiated concurrently. level = getattr(logging, self.args.log_level.upper()) @@ -189,10 +194,7 @@ def processor(logger, method_name, event_dict): # TODO set mode and encoding appropriately streams.append(open(self.args.log_file, 'a')) - if len(streams) == 0: - # no logging configured at all - # TODO what do we do in such cases ? - return + assert len(streams) != 0, "cannot configure logger for 0 streams" stream = streams[0] if len(streams) == 1 else Stream(*streams) atexit.register(stream.close) @@ -214,6 +216,10 @@ def processor(logger, method_name, event_dict): self._GLOBAL_LOG_CONFIGURED = True def init_logger(self): + if self.args.quiet and self.args.log_file is None: + # no need for a log - return a dummy + return Dummy() + self._configure_logger() # TODO bind relevant things to the basescript here ? name / hostname etc ? diff --git a/basescript/utils.py b/basescript/utils.py new file mode 100644 index 0000000..7cddc38 --- /dev/null +++ b/basescript/utils.py @@ -0,0 +1,9 @@ +class Dummy(object): + def __init__(self, *args, **kwargs): + pass + + def __call__(self, *args, **kwargs): + return self + + def __getattr__(self, *args, **kwargs): + return self diff --git a/setup.py b/setup.py index 8908870..66d677e 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ def get_long_description(): long_description = get_long_description() -version = '0.1.9' +version = '0.1.10' setup( name="basescript", version=version,