Skip to content

Commit

Permalink
Add util.logging.FallbackHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
opcode81 committed Apr 30, 2024
1 parent f4f9129 commit 1d5d3d3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
* Add line number to default format (`LOG_DEFAULT_FORMAT`)
* Add function `is_enabled` to check whether a log handler is registered
* Add context manager `LoggingDisabledContext` to temporarily disable logging
* Add `FallbackHandler` to support logging to a fallback destination (if no other handlers are defined)
* `util.io`:
* `ResultWriter`:
* Allow to disable an instance such that no results are written (constructor parameter `enabled`)
Expand Down
20 changes: 20 additions & 0 deletions src/sensai/util/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,23 @@ def __enter__(self):

def __exit__(self, exc_type, exc_value, traceback):
lg.disable(self._previous_level)


# noinspection PyShadowingBuiltins
class FallbackHandler(Handler):
"""
A log handler which applies the given handler only if the root logger has no defined handlers (or no handlers other than
this fallback handler itself)
"""
def __init__(self, handler: Handler, level=NOTSET):
"""
:param handler: the handler to which messages shall be passed on
:param level: the minimum level to output; if NOTSET, pass on everything
"""
super().__init__(level=level)
self._handler = handler

def emit(self, record):
root_handlers = getLogger().handlers
if len(root_handlers) == 0 or (len(root_handlers) == 1 and root_handlers[0] == self):
self._handler.emit(record)

0 comments on commit 1d5d3d3

Please sign in to comment.