From 8af8a4abc4539886472d8e2c19a1f74c1c4b72fa Mon Sep 17 00:00:00 2001 From: programmingAthlete Date: Fri, 29 Dec 2023 11:58:13 +0100 Subject: [PATCH] fix logging wrapper --- setup.py | 2 +- src/crypto_pkg/utils/logging.py | 12 +++++--- tests/test_logger.py | 49 +++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 tests/test_logger.py diff --git a/setup.py b/setup.py index c90e7bc..00a2cfa 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,6 @@ from setuptools import setup, find_packages -__version__ = "1.5.0" +__version__ = "1.5.1" with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() diff --git a/src/crypto_pkg/utils/logging.py b/src/crypto_pkg/utils/logging.py index 6ce50cd..1650336 100644 --- a/src/crypto_pkg/utils/logging.py +++ b/src/crypto_pkg/utils/logging.py @@ -1,3 +1,4 @@ +import inspect import logging from crypto_pkg import settings @@ -9,14 +10,17 @@ def get_logger(location: str = __name__): return log -def set_level(logger): +def set_level(logger: logging.Logger, level: int = logging.DEBUG): def deco(func): def wrapper(*args, **kwargs): _verbose = kwargs.get('_verbose', None) - if _verbose is None and len(args) == 5: - _verbose = args[4] + if _verbose is None: + params = inspect.signature(func).parameters + default_verbose = params.get('_verbose', {}).default + _verbose = next((arg_value for i, arg_value in enumerate(args) if list(params)[i] == '_verbose'), + default_verbose) if _verbose is True: - logger.setLevel(logging.DEBUG) + logger.setLevel(level) return func(*args, **kwargs) return wrapper diff --git a/tests/test_logger.py b/tests/test_logger.py new file mode 100644 index 0000000..f1624b1 --- /dev/null +++ b/tests/test_logger.py @@ -0,0 +1,49 @@ +import logging +import unittest + +from crypto_pkg.utils.logging import get_logger, set_level + +log = get_logger() + + +class TestLogger(unittest.TestCase): + + def test_logger_dec_without_level(self): + @set_level(log) + def func(_a: int, _verbose=False): + pass + + log.setLevel(logging.INFO) + + func(_a=1) + self.assertEqual(log.level, logging.INFO) + func(1) + self.assertEqual(log.level, logging.INFO) + + func(_a=1, _verbose=True) + self.assertEqual(log.level, logging.DEBUG) + + log.setLevel(logging.INFO) + + func(1, True) + self.assertEqual(log.level, logging.DEBUG) + + def test_logger_dec_with_level(self): + @set_level(logger=log, level=logging.ERROR) + def func(_a: int, _verbose=False): + pass + + log.setLevel(logging.INFO) + + func(_a=1) + self.assertEqual(log.level, logging.INFO) + func(1) + self.assertEqual(log.level, logging.INFO) + + func(_a=1, _verbose=True) + self.assertEqual(log.level, logging.ERROR) + + log.setLevel(logging.INFO) + + func(1, True) + self.assertEqual(log.level, logging.ERROR)