From a551ee5b996d8f3d1e7c5f7ebfec9dd7a08dc14e Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Sat, 24 Oct 2026 13:54:43 -0700 Subject: [PATCH] fix: raise RuntimeError from get_request_logger before request instrumentation get_request_logger() read the configurator's _instance attribute, which only exists after the configurator has been instantiated, so calling it after init_() but before init_request_instrument() raised AttributeError instead of the intended RuntimeError. Signed-off-by: Srinivas Chippagiri --- CHANGELOG.md | 4 ++++ json_logging/__init__.py | 3 ++- tests/test_get_request_logger.py | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 tests/test_get_request_logger.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8782910..88d2a42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ This project adheres to [Semantic Versioning](http://semver.org/). The format is based on [Keep a Changelog](http://keepachangelog.com/). ## Unreleased +### Fixed + +- `get_request_logger()` now raises the documented `RuntimeError` instead of `AttributeError` when called before `init_request_instrument()`. + ## 1.6.0 - 2026-10-21 ### Added diff --git a/json_logging/__init__.py b/json_logging/__init__.py index 3c30552..add1870 100644 --- a/json_logging/__init__.py +++ b/json_logging/__init__.py @@ -187,7 +187,8 @@ def get_request_logger(): "request_logger is only available if json_logging is inited with a web app, " "call init_() to do that") - instance = _current_framework['app_request_instrumentation_configurator']._instance + # _instance only exists once the configurator has been instantiated by init_request_instrument() + instance = getattr(_current_framework['app_request_instrumentation_configurator'], '_instance', None) if instance is None: raise RuntimeError("please init request instrument first, call init_request_instrument(app) to do that") diff --git a/tests/test_get_request_logger.py b/tests/test_get_request_logger.py new file mode 100644 index 0000000..fac14bb --- /dev/null +++ b/tests/test_get_request_logger.py @@ -0,0 +1,17 @@ +"""get_request_logger() error handling before request instrumentation is configured.""" +import pytest +from helpers.imports import undo_imports_from_package + + +@pytest.fixture +def fresh_json_logging(): + undo_imports_from_package("json_logging") + import json_logging + yield json_logging + undo_imports_from_package("json_logging") + + +def test_get_request_logger_after_init_but_before_request_instrumentation_raises_runtime_error(fresh_json_logging): + fresh_json_logging.init_flask() + with pytest.raises(RuntimeError, match="init request instrument first"): + fresh_json_logging.get_request_logger()