Skip to content

Commit

Permalink
[Cleanup] Simplify logging
Browse files Browse the repository at this point in the history
  • Loading branch information
klieret committed May 4, 2019
1 parent 0f573f4 commit 4f95cb9
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 59 deletions.
2 changes: 1 addition & 1 deletion ankipandas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from ankipandas.core_functions import *
from ankipandas.convenience_functions import *
from ankipandas.ankidf import *
from ankipandas.util.log import get_logger
from ankipandas.util.log import log, set_log_level
6 changes: 3 additions & 3 deletions ankipandas/convenience_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

# ours
import ankipandas.core_functions as apd
from ankipandas.util.log import get_logger
from ankipandas.util.log import log


def load_notes(
Expand Down Expand Up @@ -169,7 +169,7 @@ def find_database(
pathlib.Path to the anki2 database
"""
if not search_paths:
get_logger().info(
log.info(
"Searching for database. This might take some time. "
"You can speed this up by specifying a search path or "
"directly entering the path to your database."
Expand Down Expand Up @@ -232,7 +232,7 @@ def find_database(
)
)
found = found[0]
get_logger().debug("Database found at '{}'.".format(found))
log.debug("Database found at '{}'.".format(found))
return found


Expand Down
9 changes: 8 additions & 1 deletion ankipandas/util/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
#!/usr/bin/env python3

""" Various utilities. """
""" Various utilities of this package.
.. warning::
These utilties are less aimed at end users and might therefore be subject
to change.
"""

import ankipandas.util.dataframe
import ankipandas.util.docstrings
Expand Down
88 changes: 39 additions & 49 deletions ankipandas/util/log.py
Original file line number Diff line number Diff line change
@@ -1,63 +1,53 @@
#!/usr/bin/env python3

# std
import colorlog
import logging
from typing import Union

try:
import colorlog
except ImportError:
colorlog = None

LOG_DEFAULT_LEVEL = logging.WARNING

def get_logger(name="AnkiPandas", level=logging.WARNING,
sh_level=logging.WARNING):
"""Sets up a logging.Logger.

If the colorlog module is available, the logger will use colors,
otherwise it will be in b/w. The colorlog module is available at
https://github.com/borntyping/python-colorlog but can also easily be
installed with e.g. 'sudo pip3 colorlog' or similar commands.
def get_logger():
""" Sets up global logger. """
_log = colorlog.getLogger("AnkiPandas")

Args:
name: name of the logger
level: General logging level
sh_level: Logging level of stream handler
Returns:
Logger
"""
if colorlog:
_logger = colorlog.getLogger(name)
else:
_logger = logging.getLogger(name)

if _logger.handlers:
if _log.handlers:
# the logger already has handlers attached to it, even though
# we didn't add it ==> logging.get_logger got us an existing
# logger ==> we don't need to do anything
return _logger

_logger.setLevel(level)
if colorlog is not None:
sh = colorlog.StreamHandler()
log_colors = {
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red'
}
formatter = colorlog.ColoredFormatter(
'%(log_color)s%(name)s:%(levelname)s:%(message)s',
log_colors=log_colors)
else:
# no colorlog available:
sh = logging.StreamHandler()
formatter = logging.Formatter('%(name)s:%(levelname)s:%(message)s')
return _log

_log.setLevel(LOG_DEFAULT_LEVEL)

sh = colorlog.StreamHandler()
log_colors = {
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red'
}
formatter = colorlog.ColoredFormatter(
'%(log_color)s%(levelname)s: %(message)s',
log_colors=log_colors
)
sh.setFormatter(formatter)
sh.setLevel(sh_level)
_logger.addHandler(sh)
# Controlled by overall logger level
sh.setLevel(logging.DEBUG)

_log.addHandler(sh)

return _log


# todo: doc
def set_log_level(level: Union[str, int]):
lvl = level
if isinstance(level, str):
lvl = getattr(logging, level.upper())
get_logger().setLevel(lvl)

if colorlog is None:
_logger.debug("Module colorlog not available. Log will be b/w.")

return _logger
log = get_logger()
27 changes: 27 additions & 0 deletions ankipandas/util/test/test_log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/env python3

# std
import unittest

# ours
from ankipandas.util.log import log, get_logger, set_log_level


class TestLogging(unittest.TestCase):
""" Only tests that things run without error. """
def test_log(self):
log.info("Test info")
log.warning("Test warning")

def test_get_logger(self):
get_logger().info("Test info")
get_logger().warning("Test warning")

def test_set_log_level(self):
set_log_level("warning")
set_log_level("WARNING")
set_log_level(0)


if __name__ == "__main__":
unittest.main()
12 changes: 7 additions & 5 deletions doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ Load your anki database as a pandas DataFrame with just one
line of code!

.. toctree::
:maxdepth: 2
:maxdepth: 2

readme
ankidf
convenience_functions
core_functions
util

readme
ankidf
convenience_functions
core_functions
19 changes: 19 additions & 0 deletions doc/util.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Utilities
=========

.. module:: ankipandas.util

.. automodule:: ankipandas.util

.. automodule:: ankipandas.util.log
:members:
:undoc-members:

.. automodule:: ankipandas.util.dataframe
:members:
:undoc-members:

.. automodule:: ankipandas.util.docstrings
:members:
:undoc-members:

0 comments on commit 4f95cb9

Please sign in to comment.