diff --git a/python/nav/util.py b/python/nav/util.py index edb8d9c93f..e6ef429014 100644 --- a/python/nav/util.py +++ b/python/nav/util.py @@ -535,3 +535,18 @@ def resource_bytes(package, filename): """ ref = resource_files(package) / filename return ref.read_bytes() + + +def check_log_level(logger, loglevel): + """ + Check that the level of the logger is equal to or below loglevel + + Use before possibly expensive logging operations, like calling logging in + a loop or building an expensive object that will be logged and thrown away. + + Avoid this classic mistake: + + logger.info("%s", expensive_function()) + """ + level = logger.getEffectiveLevel() + return level <= loglevel diff --git a/python/nav/web/auth/remote_user.py b/python/nav/web/auth/remote_user.py index 896c1d14bc..b3734be6cc 100644 --- a/python/nav/web/auth/remote_user.py +++ b/python/nav/web/auth/remote_user.py @@ -20,10 +20,13 @@ from os.path import join import secrets +from django.conf import settings + from nav.auditlog.models import LogEntry from nav.config import NAVConfigParser from nav.models.profiles import Account from nav.web.auth.utils import set_account +from nav.util import check_log_level __all__ = [] @@ -178,6 +181,10 @@ def get_username(request): if not request: return None + if settings.DEBUG or check_log_level(_logger, logging.DEBUG): + for metakey, value in request.META.items(): + if metakey[0] == metakey[0].upper(): + _logger.debug('%s: %s', metakey, value) workaround = 'none' try: workaround_config = _config.get('remote-user', 'workaround') diff --git a/tests/unittests/util_test.py b/tests/unittests/util_test.py new file mode 100644 index 0000000000..a76e9f18ee --- /dev/null +++ b/tests/unittests/util_test.py @@ -0,0 +1,17 @@ +import logging + +import pytest + +from nav.util import check_log_level + + +class TestCheckLogLevel: + def test_actual_loglevel_above_input_should_return_false(self, *_): + logger = logging.getLogger() + logger.setLevel(logging.INFO) + assert check_log_level(logger, logging.DEBUG) is False + + def test_actual_loglevel_below_input_should_return_true(self, *_): + logger = logging.getLogger() + logger.setLevel(logging.INFO) + assert check_log_level(logger, logging.WARNING)