Skip to content

Commit

Permalink
logger creation removed from __init__.py
Browse files Browse the repository at this point in the history
  • Loading branch information
epogrebnyak committed Aug 10, 2019
1 parent c0476b8 commit 243b10b
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 13 deletions.
12 changes: 0 additions & 12 deletions handout/__init__.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 2 additions & 1 deletion handout/handout.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import shutil

from handout import blocks
from handout import tools


class Handout(object):
Expand All @@ -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
Expand Down
7 changes: 7 additions & 0 deletions handout/tests/test_tools.py
Original file line number Diff line number Diff line change
@@ -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
17 changes: 17 additions & 0 deletions handout/tools.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import sys
import logging

def strip_empty_lines(lines):
output = []
for line in lines:
Expand All @@ -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

0 comments on commit 243b10b

Please sign in to comment.