diff --git a/nuclio_sdk/logger.py b/nuclio_sdk/logger.py index 8dfa27f..45a899c 100644 --- a/nuclio_sdk/logger.py +++ b/nuclio_sdk/logger.py @@ -58,16 +58,18 @@ def __init__(self, level, name="nuclio_sdk"): self._logger = logging.getLogger(name) self._logger.setLevel(level) self._bound_variables = {} - self._handlers = {} def set_handler(self, handler_name, file, formatter): # check if there's a handler by this name - if handler_name in self._handlers: - self._logger.removeHandler(self._handlers[handler_name]) + for handler in self._logger.handlers: + if handler.name == handler_name: + self._logger.removeHandler(handler) + break # create a stream handler from the file stream_handler = logging.StreamHandler(file) + stream_handler.name = handler_name # set the formatter stream_handler.setFormatter(formatter) @@ -75,9 +77,6 @@ def set_handler(self, handler_name, file, formatter): # add the handler to the logger self._logger.addHandler(stream_handler) - # save as the named output - self._handlers[handler_name] = stream_handler - def debug(self, message, *args): self._update_bound_vars_and_log(logging.DEBUG, message, *args) diff --git a/nuclio_sdk/test/test_logger.py b/nuclio_sdk/test/test_logger.py index 01a2c67..e0639c7 100644 --- a/nuclio_sdk/test/test_logger.py +++ b/nuclio_sdk/test/test_logger.py @@ -110,3 +110,21 @@ def __log__(self): '"with": {"some_instance": "Unable to serialize object: I am not a string"}', self._io.getvalue(), ) + + def test_redundant_logger_creation(self): + + # create 3 loggers with the same name + logger1 = nuclio_sdk.Logger(logging.DEBUG, "test-logger") + logger1.set_handler("default", self._io, nuclio_sdk.logger.JSONFormatter()) + logger2 = nuclio_sdk.Logger(logging.DEBUG, "test-logger") + logger2.set_handler("default", self._io, nuclio_sdk.logger.JSONFormatter()) + logger3 = nuclio_sdk.Logger(logging.DEBUG, "test-logger") + logger3.set_handler("default", self._io, nuclio_sdk.logger.JSONFormatter()) + + # log from each logger and make sure only one log line is printed + logger1.info("1") + assert self._io.getvalue().count('"level": "info", "message": "1"') == 1 + logger2.info("2") + assert self._io.getvalue().count('"level": "info", "message": "2"') == 1 + logger3.info("3") + assert self._io.getvalue().count('"level": "info", "message": "3"') == 1