diff --git a/adafruit_logging.py b/adafruit_logging.py index e9f7c4b..a095315 100644 --- a/adafruit_logging.py +++ b/adafruit_logging.py @@ -95,28 +95,35 @@ def emit(self, level, msg): # pylint:disable=undefined-variable logger_cache = dict() +null_logger = None - +# pylint:disable=global-statement def getLogger(name): """Create or retrieve a logger by name. - :param name: the name of the logger to create/retrieve + :param name: the name of the logger to create/retrieve None will cause the + NullLogger instance to be returned. """ + global null_logger + if not name or name == "": + if not null_logger: + null_logger = NullLogger() + return null_logger + if name not in logger_cache: logger_cache[name] = Logger() return logger_cache[name] +# pylint:enable=global-statement + + class Logger: """Provide a logging api.""" def __init__(self): - """Create an instance. - - :param handler: what to use to output messages. Defaults to a PrintHandler. - - """ + """Create an instance.""" self._level = NOTSET self._handler = PrintHandler() @@ -201,3 +208,39 @@ def critical(self, format_string, *args): """ self.log(CRITICAL, format_string, *args) + + +class NullLogger: + """Provide an empty logger. + This can be used in place of a real logger to more efficiently disable logging.""" + + def __init__(self): + """Dummy implementation.""" + + def setLevel(self, value): + """Dummy implementation.""" + + def getEffectiveLevel(self): + """Dummy implementation.""" + return NOTSET + + def addHandler(self, hldr): + """Dummy implementation.""" + + def log(self, level, format_string, *args): + """Dummy implementation.""" + + def debug(self, format_string, *args): + """Dummy implementation.""" + + def info(self, format_string, *args): + """Dummy implementation.""" + + def warning(self, format_string, *args): + """Dummy implementation.""" + + def error(self, format_string, *args): + """Dummy implementation.""" + + def critical(self, format_string, *args): + """Dummy implementation.""" diff --git a/examples/logging_simpletest.py b/examples/logging_simpletest.py index c5ac6c2..3286bce 100644 --- a/examples/logging_simpletest.py +++ b/examples/logging_simpletest.py @@ -2,12 +2,32 @@ # SPDX-License-Identifier: MIT # pylint:disable=undefined-variable,wildcard-import,no-name-in-module -# pylint:disable=no-member +# pylint:disable=no-member,invalid-name + +"""Briefly exercise the logger and null logger.""" import adafruit_logging as logging +# This should produce an error output + logger = logging.getLogger("test") logger.setLevel(logging.ERROR) logger.info("Info message") logger.error("Error message") + +# This should produce no output + +null_logger = logging.getLogger(None) + +null_logger.setLevel(logging.ERROR) +null_logger.info("Info message") +null_logger.error("Error message") + +# This should produce no output + +null_logger = logging.getLogger("") + +null_logger.setLevel(logging.ERROR) +null_logger.info("Info message") +null_logger.error("Error message")