factor out logger object initialisation

This commit is contained in:
Antoine Beaupré 2015-10-06 11:06:50 -04:00
parent 2d0dae4e8b
commit 26561a7766
2 changed files with 26 additions and 2 deletions

View File

@ -1,3 +1,4 @@
import inspect
import logging
import sys
@ -17,3 +18,23 @@ def setup_logging(args, stream=None):
l.setLevel(levels[args.verbose])
return sh,
def find_parent_module():
"""find the name of a the first module calling this module
if we cannot find it, we return the current module's name
(__name__) instead.
"""
try:
frame = inspect.currentframe().f_back
module = inspect.getmodule(frame)
while module is None or module.__name__ == __name__:
frame = frame.f_back
module = inspect.getmodule(frame)
return module.__name__
except AttributeError:
# somehow we failed to find our module
# return the logger module name by default
return __name__
def create_logger(name=None):
return logging.getLogger(name or find_parent_module())

View File

@ -8,8 +8,8 @@ import sys
from mock import Mock
import pytest
from ..logger import setup_logging
logger = logging.getLogger(__name__)
from ..logger import find_parent_module, create_logger, setup_logging
logger = create_logger()
@pytest.fixture()
def io_logger():
@ -38,3 +38,6 @@ def test_multiple_loggers(io_logger):
logger = logging.getLogger('borg.testsuite.logger')
logger.info('hello world 2')
assert io_logger.getvalue() == "borg.testsuite.logger: hello world 2\n"
def test_parent_module():
assert find_parent_module() == __name__