Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add logger #14

Merged
merged 1 commit into from
Sep 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ jobs:

- name: Run tests
run: |
export PYTHONPATH=`pwd`
pytest
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,22 @@ Please note, DIY Hotspots do not earn HNT.
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| Pi Supply IoT LoRa Gateway HAT | RPi | DIY-PISLGH | 0.0 | 22 | | | Light | False | Any pi with 40 pin header |
| RAK2287 | RPi | DIY-RAK2287 | 0.0 | 17 | | | Light | False | Any pi with 40 pin header |
## utils

### logger

```python
from hm_pyhelper.utils import logger
logger = get_logger(__name__)
logger.debug("message to log")
```

## Testing

To run tests:

```bash
pip install -r requirements.txt
pip install -r test-requirements.txt
PYTHONPATH=./ pytest
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't think the explicit PYTHONPATH is required here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm unsure if this is a best practice but with the code as-is now, you'll get an error if just trying to pytest. This type of thing is a problem whenever we have the test code in a separate directory/module. In other repos, we get around it by modifying the path from the test code, which I think is worse.

✗ pytest
========================================== test session starts ===========================================
platform linux -- Python 3.7.3, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: /home/user/code/nebra/hm-pyhelper
collected 10 items / 1 error / 9 selected                                                                

================================================= ERRORS =================================================
________________________ ERROR collecting hm_pyhelper/tests/utils/test_logger.py _________________________
ImportError while importing test module '/home/user/code/nebra/hm-pyhelper/hm_pyhelper/tests/utils/test_logger.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/home/user/.pyenv/versions/3.7.3/lib/python3.7/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/utils/test_logger.py:2: in <module>
    from utils.logger import get_logger, _log_format

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pwd should be in PYTHONPATH, but this is not a big deal.

```
28 changes: 28 additions & 0 deletions hm_pyhelper/tests/utils/test_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from unittest import TestCase
from hm_pyhelper.utils.logger import get_logger, _log_format
import re
import logging


class TestExample(TestCase):
def test_logging(self):
logger = get_logger(__name__)

with self.assertLogs() as captured:
logger.debug("Hello world.")

# check that there is only one log message
self.assertEqual(len(captured.records), 1)
record = captured.records[0]
formatter = logging.Formatter(_log_format)
formatted_output = formatter.format(record)

# Do not check timestamp and filepath because those change
# based on the environment and run time
expected_partial_output_regex = re.escape(
" - [DEBUG] - test_logger - (test_logger.py).test_logging -- ")
expected_output_regex = ".*" + \
expected_partial_output_regex + ".*" + \
" - Hello world."
are_logs_correct = re.search(expected_output_regex, formatted_output)
self.assertTrue(are_logs_correct)
23 changes: 23 additions & 0 deletions hm_pyhelper/utils/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import os
import logging

LOGLEVEL = os.environ.get("LOGLEVEL", "DEBUG")
_log_format = f"%(asctime)s - [%(levelname)s] - %(name)s - (%(filename)s).%(funcName)s -- %(pathname)s:(%(lineno)d) - %(message)s" # noqa: F541 E501


def get_stream_handler():
stream_handler = logging.StreamHandler()
stream_handler.setLevel(LOGLEVEL)
stream_handler.setFormatter(logging.Formatter(_log_format))
return stream_handler


def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(LOGLEVEL)
logger.addHandler(get_stream_handler())
return logger


def log(class_name):
return get_logger(class_name)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

setup(
name='hm_pyhelper',
version='0.6.1',
version='0.6.3',
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This had to be bumped twice because of this: #20

author="Nebra Ltd",
author_email="[email protected]",
description="Helium Python Helper",
Expand Down