Skip to content

Commit

Permalink
[Logger] Fix multiple logs (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomerShor authored Jun 20, 2023
1 parent 3930947 commit c3bd4ca
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
11 changes: 5 additions & 6 deletions nuclio_sdk/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,26 +58,25 @@ 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)

# 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)

Expand Down
18 changes: 18 additions & 0 deletions nuclio_sdk/test/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit c3bd4ca

Please sign in to comment.