Skip to content

Commit

Permalink
Merge pull request #4 from dastels/master
Browse files Browse the repository at this point in the history
Make more like CPython's logger
  • Loading branch information
makermelissa authored Mar 13, 2019
2 parents 3d4a850 + 07a4070 commit 6355873
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 36 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ install:
- pip install --force-reinstall pylint==1.9.2

script:
- pylint adafruit_logger.py
- pylint adafruit_logging.py
- ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace examples/*.py)
- circuitpython-build-bundles --filename_prefix adafruit-circuitpython-logger --library_location .
- cd docs && sphinx-build -E -W -b html . _build/html && cd ..
10 changes: 5 additions & 5 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ Usage Example

.. code-block:: python
from adafruit_logger import Logger, ERROR, INFO
import adafruit_logging as logging
logger = Logger()
logger = logging.getLogger('test')
logger.level = ERROR
logger.log(INFO, 'Info message')
logger.log(ERROR, 'Error message')
logger.setLevel(logging.ERROR)
logger.info('Info message')
logger.error('Error message')
Contributing
Expand Down
61 changes: 39 additions & 22 deletions adafruit_logger.py → adafruit_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`adafruit_logger`
`adafruit_logging`
================================================================================
Logging module for CircuitPython
Expand All @@ -41,6 +41,7 @@
"""
#pylint:disable=redefined-outer-name,consider-using-enumerate,no-self-use
#pylint:disable=invalid-name

import time

Expand All @@ -65,7 +66,9 @@ def level_for(value):
"""
for i in range(len(LEVELS)):
if value < LEVELS[i][0]:
if value == LEVELS[i][0]:
return LEVELS[i][1]
elif value < LEVELS[i][0]:
return LEVELS[i-1][1]
return LEVELS[0][1]

Expand All @@ -79,11 +82,7 @@ def format(self, level, msg):
:param msg: the message to log
"""
now = time.localtime()
time_vals = (now.tm_year, now.tm_mon, now.tm_mday,
now.tm_hour, now.tm_min, now.tm_sec)
timestamp = '%4d/%02d/%02d %02d:%02d:%02d' % time_vals
return '{0}: {1} - {2}'.format(timestamp, level_for(level), msg)
return '{0}: {1} - {2}'.format(time.monotonic(), level_for(level), msg)

def emit(self, level, msg):
"""Send a message where it should go.
Expand All @@ -108,30 +107,48 @@ def emit(self, level, msg):
# The level module-global variables get created when loaded
#pylint:disable=undefined-variable

logger_cache = dict()

def getLogger(name):
"""Create or retrieve a logger by name.
:param name: the name of the logger to create/retrieve
"""
if name not in logger_cache:
logger_cache[name] = Logger()
return logger_cache[name]

class Logger(object):
"""Provide a logging api."""

def __init__(self, handler=None):
def __init__(self):
"""Create an instance.
:param handler: what to use to output messages. Defaults to a PrintHandler.
"""
self._level = NOTSET
if handler is None:
self._handler = PrintHandler()
else:
self._handler = handler

@property
def level(self):
"""The level."""
return self._level

@level.setter
def level(self, value):
self._handler = PrintHandler()

def setLevel(self, value):
"""Set the logging cuttoff level.
:param value: the lowest level to output
"""
self._level = value

def addHandler(self, hldr):
"""Sets the handler of this logger to the specified handler.
*NOTE* this is slightly different from the CPython equivalent which adds
the handler rather than replaceing it.
:param hldr: the handler
"""
self._handler = hldr

def log(self, level, format_string, *args):
"""Log a message.
Expand All @@ -140,8 +157,8 @@ def log(self, level, format_string, *args):
:param args: arguments to ``format_string.format()``, can be empty
"""
if self._level != NOTSET and level >= self._level:
self._handler.emit(level, format_string.format(*args))
if level >= self._level:
self._handler.emit(level, format_string % args)

def debug(self, format_string, *args):
"""Log a debug message.
Expand Down
2 changes: 1 addition & 1 deletion docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
.. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py)
.. use this format as the module name: "adafruit_foo.foo"
.. automodule:: adafruit_logger
.. automodule:: adafruit_logging
:members:
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
# Uncomment the below if you use native CircuitPython modules such as
# digitalio, micropython and busio. List the modules you use. Without it, the
# autodoc module docs will fail to generate with a warning.
# autodoc_mock_imports = ["digitalio", "busio"]
#autodoc_mock_imports = ["digitalio", "busio"]


intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)}
Expand Down
12 changes: 7 additions & 5 deletions examples/logger_simpletest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#pylint:disable=undefined-variable,wildcard-import,no-name-in-module
from adafruit_logger import Logger, ERROR, INFO
#pylint:disable=no-member

logger = Logger()
import adafruit_logging as logging

logger.level = ERROR
logger.log(INFO, 'Info message')
logger.log(ERROR, 'Error message')
logger = logging.getLogger('test')

logger.setLevel(logging.ERROR)
logger.info('Info message')
logger.error('Error message')
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,5 @@
# simple. Or you can use find_packages().
# TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER,
# CHANGE `py_modules=['...']` TO `packages=['...']`
py_modules=['adafruit_logger'],
py_modules=['adafruit_logging'],
)

0 comments on commit 6355873

Please sign in to comment.