diff --git a/handout/__init__.py b/handout/__init__.py index de017c7..7498bcf 100644 --- a/handout/__init__.py +++ b/handout/__init__.py @@ -1,13 +1 @@ -import sys -import logging - from .handout import Handout - - -# Set up logger. -logger = logging.getLogger('handout') -logger.setLevel(logging.INFO) -logger.propagate = False # Global logger should not print messages again. -handler = logging.StreamHandler(sys.stdout) -handler.setFormatter(logging.Formatter('%(message)s')) -logger.addHandler(handler) diff --git a/handout/handout.py b/handout/handout.py index 4f9b087..8f88c95 100644 --- a/handout/handout.py +++ b/handout/handout.py @@ -6,6 +6,7 @@ import shutil from handout import blocks +from handout import tools class Handout(object): @@ -16,7 +17,7 @@ def __init__(self, directory, title='Handout'): self._title = title self._blocks = collections.defaultdict(list) self._pending = [] - self._logger = logging.getLogger('handout') + self._logger = tools.get_logger() for info in inspect.stack(): if info.filename == __file__: continue diff --git a/handout/tests/test_tools.py b/handout/tests/test_tools.py new file mode 100644 index 0000000..1382ca3 --- /dev/null +++ b/handout/tests/test_tools.py @@ -0,0 +1,7 @@ +import handout + +def test_get_logger_has_single_handler(): + import handout # Simulate multiple imports of a package. + import handout + logger = handout.tools.get_logger() + assert len(logger.handlers) == 1 \ No newline at end of file diff --git a/handout/tools.py b/handout/tools.py index fedc630..7643ef1 100644 --- a/handout/tools.py +++ b/handout/tools.py @@ -1,3 +1,6 @@ +import sys +import logging + def strip_empty_lines(lines): output = [] for line in lines: @@ -12,3 +15,17 @@ def strip_empty_lines(lines): output.append(line) lines = reversed(output) return list(lines) + + +def get_logger(): + logger = logging.getLogger('handout') + logger.setLevel(logging.INFO) # A user can change this level later. + logger.propagate = False # Global logger should not print messages again. + if not logger.handlers: # Prevents creation of multiple handlers. + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(logging.Formatter('%(message)s')) + logger.addHandler(handler) + # The logger can be accessed anywhere in code by its name with + # `logging.getLogger('handout')`. However, we retrun the logger + # explcitly here as function result, for convenience of use. + return logger