Skip to content

Commit

Permalink
Add enable/disable functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Delgan committed Dec 6, 2018
1 parent 2ad6aa1 commit 27f4a35
Show file tree
Hide file tree
Showing 5 changed files with 146 additions and 10 deletions.
55 changes: 47 additions & 8 deletions loguru/_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ class Logger:
_handlers = {}
_levels = _default_levels.copy()
_min_level = float("inf")
_enabled = {}
_activation_list = []

def __init__(self, *, extra={}, record=False, exception=False, lazy=False):
self.catch = Catcher(self)
Expand Down Expand Up @@ -132,6 +134,36 @@ def reset(self):
self._levels.update(self._default_levels)
self.extra.clear()

def configure(self, config):
self.extra.update(config.get('extra', {}))
for params in config.get('levels', []):
self.level(**params)
handlers_ids = [self.start(**params) for params in config.get('sinks', [])]
return handlers_ids

def _change_activation(self, name, status):
if name != '':
name += '.'

activation_list = [(n, s) for n, s in self._activation_list if n[:len(name)] != name]

parent_status = next((s for n, s in activation_list if name[:len(n)] == n), None)
if parent_status != status and not (name == '' and status == True):
activation_list.append((name, status))
activation_list.sort(key=lambda x: x[0].count('.'), reverse=True)

for n in self._enabled:
if (n + '.')[:len(name)] == name:
self._enabled[n] = status

self._activation_list[:] = activation_list

def enable(self, name):
self._change_activation(name, True)

def disable(self, name):
self._change_activation(name, False)

def start(self, sink, *, level=_constants.LOGURU_LEVEL, format=_constants.LOGURU_FORMAT,
colored=_constants.LOGURU_COLORED, structured=_constants.LOGURU_STRUCTURED,
enhanced=_constants.LOGURU_ENHANCED, filter=None, **kwargs):
Expand Down Expand Up @@ -240,13 +272,6 @@ def stop(self, handler_id=None):
return 1
return 0

def configure(self, config):
self.extra.update(config.get('extra', {}))
for params in config.get('levels', []):
self.level(**params)
handlers_ids = [self.start(**params) for params in config.get('sinks', [])]
return handlers_ids

def log(_self, _level, _message, *args, **kwargs):
_self._log(_level, False, 3, False, _message, *args, **kwargs)

Expand Down Expand Up @@ -275,7 +300,21 @@ def log_function(_self, _message, *args, **kwargs):
frame = getframe(frame_idx)
name = frame.f_globals['__name__']

# TODO: Early exit if no handler
if not _self._handlers:
return

try:
if not _self._enabled[name]:
return
except KeyError:
dotted_name = name + '.'
for dotted_module_name, status in _self._activation_list:
if dotted_name[:len(dotted_module_name)] == dotted_module_name:
if status:
break
_self._enabled[name] = False
return
_self._enabled[name] = True

now = pendulum_now()
now._FORMATTER = 'alternative'
Expand Down
2 changes: 2 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ def logger():
yield loguru.logger
loguru.logger.reset()
loguru._logger.Logger._handlers_count = itertools.count()
loguru._logger.Logger._enabled.clear()
loguru._logger.Logger._activation_list.clear()

@pytest.fixture
def writer():
Expand Down
93 changes: 93 additions & 0 deletions tests/test_activation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import pytest

@pytest.mark.parametrize('name, should_log', [
('', False),
('tests', False),
('test', True),
('testss', True),
('tests.', True),
('tests.test_activation', False),
('tests.test_activation.', True),
('test_activation', True),
('.', True),
])
def test_disable(logger, writer, name, should_log):
logger.start(writer, format="{message}")
logger.disable(name)
logger.debug("message")
result = writer.read()

if should_log:
assert result == "message\n"
else:
assert result == ""

@pytest.mark.parametrize('name, should_log', [
('', True),
('tests', True),
('test', False),
('testss', False),
('tests.', False),
('tests.test_activation', True),
('tests.test_activation.', False),
('test_activation', False),
('.', False),
])
def test_enable(logger, writer, name, should_log):
logger.start(writer, format="{message}")
logger.disable("")
logger.enable(name)
logger.debug("message")
result = writer.read()

if should_log:
assert result == "message\n"
else:
assert result == ""

def test_log_before_enable(logger, writer):
logger.start(writer, format="{message}")
logger.disable("")
logger.debug("nope")
logger.enable("tests")
logger.debug("yes")
result = writer.read()
assert result == "yes\n"

def test_log_before_disable(logger, writer):
logger.start(writer, format="{message}")
logger.enable("")
logger.debug("yes")
logger.disable("tests")
logger.debug("nope")
result = writer.read()
assert result == "yes\n"

def test_multiple_activations(logger):
n = lambda: len(logger._activation_list)

assert n() == 0
logger.enable("")
assert n() == 0
logger.disable("")
assert n() == 1
logger.enable('foo')
assert n() == 2
logger.enable('foo.bar')
assert n() == 2
logger.disable('foo')
assert n() == 1
logger.disable('foo.bar')
assert n() == 1
logger.enable('foo.bar')
assert n() == 2
logger.disable('foo.bar.baz')
assert n() == 3
logger.disable('foo.baz')
assert n() == 3
logger.disable('foo.baz.bar')
assert n() == 3
logger.enable('foo.baz.bar')
assert n() == 4
logger.enable("")
assert n() == 0
3 changes: 2 additions & 1 deletion tests/test_clearing.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,12 @@ def test_reset_level(logger, writer):
logger.level("foo", 12)

logger.reset()
logger.start(writer, format="{message}")

with pytest.raises(Exception):
logger.log("foo", "nope")

logger.start(writer, format="{message}")

logger.log("DEBUG", "1")
logger.debug("2")
assert writer.read() == "1\n2\n"
Expand Down
3 changes: 2 additions & 1 deletion tests/test_levels.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ def test_start_custom_level(logger, writer):
assert writer.read() == 'INFO + 20 + yes\n'

@pytest.mark.parametrize("level", ["foo", -1, 3.4, object()])
def test_log_invalid_level(logger, level):
def test_log_invalid_level(logger, writer, level):
logger.start(writer)
with pytest.raises(ValueError):
logger.log(level, "test")

Expand Down

0 comments on commit 27f4a35

Please sign in to comment.