Skip to content

Commit

Permalink
Prevent double logging in setup_logger
Browse files Browse the repository at this point in the history
  • Loading branch information
psrok1 committed Jul 14, 2022
1 parent 6acee92 commit c44935c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
34 changes: 30 additions & 4 deletions karton/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@


class KartonBase(abc.ABC):
"""
Base class for all Karton services
"""

identity = ""

def __init__(
Expand All @@ -27,7 +31,9 @@ def __init__(
self.config = config or Config()
self.backend = backend or KartonBackend(self.config, identity=self.identity)

self.log_handler = KartonLogHandler(backend=self.backend, channel=self.identity)
self._log_handler = KartonLogHandler(
backend=self.backend, channel=self.identity
)
self.current_task: Optional[Task] = None

def setup_logger(self, level: Optional[Union[str, int]] = None) -> None:
Expand All @@ -54,16 +60,36 @@ def setup_logger(self, level: Optional[Union[str, int]] = None) -> None:
if not self.identity:
raise ValueError("Can't setup logger without identity")

self.log_handler.setFormatter(logging.Formatter())
self._log_handler.setFormatter(logging.Formatter())

logger = logging.getLogger(self.identity)

if logger.handlers:
# If logger already have handlers set: clear them
logger.handlers.clear()

# Turn off propagation to parent loggers to avoid double logging
# We set up StreamHandler directly on logger, so it may be needed
# in case basicConfig was called at some point.
logger.propagate = False

logger.setLevel(log_level)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(
logging.Formatter("[%(asctime)s][%(levelname)s] %(message)s")
)
logger.addHandler(stream_handler)
logger.addHandler(self.log_handler)
logger.addHandler(self._log_handler)

@property
def log_handler(self) -> KartonLogHandler:
"""
Return KartonLogHandler bound to this Karton service.
Can be used to setup logging on your own by adding this handler
to the chosen loggers.
"""
return self._log_handler

@property
def log(self) -> logging.Logger:
Expand All @@ -87,7 +113,7 @@ class KartonServiceBase(KartonBase):
"""
Karton base class for looping services.
You can set a informative version information by setting the ``version`` class
You can set an informative version information by setting the ``version`` class
attribute
:param config: Karton config to use for service configuration
Expand Down
4 changes: 3 additions & 1 deletion karton/core/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@


class KartonLogHandler(logging.Handler):
"""Base class for karton loggers"""
"""
logging.Handler that passes logs to the Karton backend.
"""

def __init__(self, backend: KartonBackend, channel: str) -> None:
logging.Handler.__init__(self)
Expand Down

0 comments on commit c44935c

Please sign in to comment.