Skip to content

Commit

Permalink
Logger Improvement (#21)
Browse files Browse the repository at this point in the history
* Added the ability to use a custom format string in the logger

* bump version
  • Loading branch information
ilyastrodubtsev authored Oct 18, 2021
1 parent 2029e19 commit d3388c9
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
18 changes: 18 additions & 0 deletions hm_pyhelper/tests/utils/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,21 @@ def test_logging(self):
" - Hello world."
are_logs_correct = re.search(expected_output_regex, formatted_output)
self.assertTrue(are_logs_correct)

def test_custom_log_format(self):
log_string = f"[%(levelname)s] - %(name)s: %(message)s" # noqa: F541 E501
log_message = "test log string"
logger = get_logger(__name__, log_string)

with self.assertLogs() as captured:
logger.info(log_message)

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

result = re.match("\\[INFO\\]\\s-\\s.*:\\s" + log_message,
formatted_output)
self.assertTrue(result)
8 changes: 4 additions & 4 deletions hm_pyhelper/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
_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():
def get_stream_handler(log_format=_log_format):
stream_handler = logging.StreamHandler()
stream_handler.setLevel(LOGLEVEL)
stream_handler.setFormatter(logging.Formatter(_log_format))
stream_handler.setFormatter(logging.Formatter(log_format))
return stream_handler


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


Expand Down
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.8.2',
version='0.8.3',
author="Nebra Ltd",
author_email="[email protected]",
description="Helium Python Helper",
Expand Down

0 comments on commit d3388c9

Please sign in to comment.