Skip to content

Commit fd4d37f

Browse files
auto-instrument: import the user handler during import (#142)
1 parent 8155956 commit fd4d37f

File tree

2 files changed

+33
-8
lines changed

2 files changed

+33
-8
lines changed

src/lumigo_tracer/sync_http/handler.py

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,36 @@
66
ORIGINAL_HANDLER_KEY = "LUMIGO_ORIGINAL_HANDLER"
77

88

9+
def parse_handler():
10+
try:
11+
module_name, unit_name = os.environ[ORIGINAL_HANDLER_KEY].rsplit(".", 1)
12+
except KeyError:
13+
raise ValueError(
14+
"Could not find the original handler. Please contact Lumigo for more information."
15+
)
16+
except ValueError:
17+
raise RuntimeError(
18+
f"Invalid handler format: Bad handler '{os.environ[ORIGINAL_HANDLER_KEY]}': not enough values to unpack (expected 2, got 1)"
19+
)
20+
importable_name = module_name.replace("/", ".")
21+
return importable_name, unit_name
22+
23+
924
@lumigo_tracer()
1025
def _handler(*args, **kwargs):
26+
handler_module = ""
1127
try:
12-
module_name, unit_name = os.environ[ORIGINAL_HANDLER_KEY].rsplit(".", 1)
13-
importable_name = module_name.replace("/", ".")
14-
original_handler = getattr(importlib.import_module(importable_name), unit_name)
28+
handler_module, unit_name = parse_handler()
29+
original_handler = getattr(importlib.import_module(handler_module), unit_name)
1530
except (ImportError, AttributeError):
1631
raise ImportError(
17-
"Could not load the original handler. Are you sure that the import is ok?"
18-
)
19-
except KeyError:
20-
raise ValueError(
21-
"Could not find the original handler. Please follow lumigo's docs: https://docs.lumigo.io/"
32+
f"Unable to import module '{handler_module}': No module named '{handler_module}'"
2233
)
2334
return original_handler(*args, **kwargs)
35+
36+
37+
try:
38+
# import handler during runtime initialization, as usual.
39+
importlib.import_module(parse_handler()[0])
40+
except Exception:
41+
pass

src/test/unit/test_handler.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,10 @@ def test_error_in_original_handler_no_extra_exception_log(monkeypatch, context):
5555
exception_occurred = True
5656
assert "another exception occurred" not in traceback.format_exc()
5757
assert exception_occurred is True
58+
59+
60+
def test_handler_bad_format(monkeypatch):
61+
monkeypatch.setenv(ORIGINAL_HANDLER_KEY, "no_method")
62+
63+
with pytest.raises(RuntimeError):
64+
_handler({}, {})

0 commit comments

Comments
 (0)