Skip to content

Commit

Permalink
Updated logging init logic to not log on setting --log=none (#323)
Browse files Browse the repository at this point in the history
* Fix "none" logging

Test for different logging levels, existing and none existing

Co-authored-by: yoavrotems <[email protected]>
Co-authored-by: Yehuda Chikvashvili <[email protected]>
  • Loading branch information
3 people authored Apr 12, 2020
1 parent 124a51d commit 6d63f55
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 10 deletions.
14 changes: 4 additions & 10 deletions kube_hunter/conf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import logging

from kube_hunter.conf.parser import parse_args
from kube_hunter.conf.logging import setup_logger

config = parse_args()
formatter = "%(asctime)s %(levelname)s %(name)s %(message)s"

loglevel = getattr(logging, config.log.upper(), None)
config = parse_args()
setup_logger(config.log)

if not loglevel:
logging.basicConfig(level=logging.INFO, format=formatter)
logging.warning("Unknown log level selected, using info")
elif config.log.lower() != "none":
logging.basicConfig(level=loglevel, format=formatter)
__all__ = [config]

import plugins # noqa
23 changes: 23 additions & 0 deletions kube_hunter/conf/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import logging


DEFAULT_LEVEL = logging.INFO
DEFAULT_LEVEL_NAME = logging.getLevelName(DEFAULT_LEVEL)
LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s"


def setup_logger(level_name):
# Remove any existing handlers
# Unnecessary in Python 3.8 since `logging.basicConfig` has `force` parameter
for h in logging.getLogger().handlers[:]:
h.close()
logging.getLogger().removeHandler(h)

if level_name.upper() == "NONE":
logging.disable(logging.CRITICAL)
else:
log_level = getattr(logging, level_name.upper(), None)
log_level = log_level if type(log_level) is int else None
logging.basicConfig(level=log_level or DEFAULT_LEVEL, format=LOG_FORMAT)
if not log_level:
logging.warning(f"Unknown log level '{level_name}', using {DEFAULT_LEVEL_NAME}")
22 changes: 22 additions & 0 deletions tests/conf/test_logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import logging

from kube_hunter.conf.logging import setup_logger


def test_setup_logger_level():
test_cases = [
("INFO", logging.INFO),
("Debug", logging.DEBUG),
("critical", logging.CRITICAL),
("NOTEXISTS", logging.INFO),
("BASIC_FORMAT", logging.INFO),
]
for level, expected in test_cases:
setup_logger(level)
actual = logging.getLogger().getEffectiveLevel()
assert actual == expected, f"{level} level should be {expected} (got {actual})"


def test_setup_logger_none():
setup_logger("NONE")
assert logging.getLogger().manager.disable == logging.CRITICAL

0 comments on commit 6d63f55

Please sign in to comment.