Skip to content

Commit

Permalink
Fix adjusting log level called with uninitialized logger (#263)
Browse files Browse the repository at this point in the history
* Fix adjusting log level called with uninitialized logger
* Add test
  • Loading branch information
zikolach authored Aug 20, 2019
1 parent d2fa051 commit e50ddf6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
9 changes: 5 additions & 4 deletions pyam/logger.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from contextlib import contextmanager
import logging
from contextlib import contextmanager

# globally accessible logger
_LOGGER = None
Expand All @@ -18,7 +18,8 @@ def logger():
@contextmanager
def adjust_log_level(level='ERROR'):
"""Context manager to change log level"""
old_level = _LOGGER.getEffectiveLevel()
_LOGGER.setLevel(level)
_logger = logger()
old_level = _logger.getEffectiveLevel()
_logger.setLevel(level)
yield
_LOGGER.setLevel(old_level)
_logger.setLevel(old_level)
13 changes: 11 additions & 2 deletions tests/test_logger.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
from pyam import logger
from pyam.logger import adjust_log_level
import sys

from pyam.logger import logger, adjust_log_level


def test_context_adjust_log_level():
assert logger().getEffectiveLevel() == 20
with adjust_log_level():
assert logger().getEffectiveLevel() == 40
assert logger().getEffectiveLevel() == 20


def test_adjusting_level_for_not_initialized_logger():
# de-initialize logger to simulate adjust_log_level called before logger
pyam_logger = sys.modules['pyam.logger']
pyam_logger._LOGGER = None
with adjust_log_level():
pass

0 comments on commit e50ddf6

Please sign in to comment.