Skip to content

Commit b434a21

Browse files
feat(observability): pass sentry_sdk.init options through SentryErrorTrackingSink (#12)
The sink fixed every sentry_sdk.init argument, so a service could express neither "do not report this expected exception type" nor "do not report probe transactions"; the redactor — the one hook it exposed — is dict -> dict and never sees the hint, so it cannot drop and should not. The sink now takes any further sentry_sdk.init argument at construction (ignore_errors, before_send, before_send_transaction, traces_sampler, integrations, ...), used through instance injection like PrometheusMetricsSink(registry=...). The settings-driven arguments stay the sink's business and are rejected at construction. A before_send given this way is composed with the redactor: it runs first with the full (event, hint) and may drop; what survives is redacted. Closes #9
1 parent ae85ffb commit b434a21

4 files changed

Lines changed: 211 additions & 8 deletions

File tree

‎docs/adapters/observability-backends.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,51 @@ sampling rates from `settings.error_tracking`. The [redactor](../concepts/observ
7575
is installed as `before_send`, so every outgoing event is filtered — including stack-frame locals
7676
and breadcrumb payloads.
7777

78+
### Everything else `sentry_sdk.init` takes
79+
80+
The settings section models the deployment facts. Anything else — `ignore_errors`, a
81+
`before_send` that drops, `before_send_transaction`, `traces_sampler`, `integrations`,
82+
`send_default_pii` — goes through the sink's constructor, via
83+
[instance injection](../concepts/observability.md#instance-injection):
84+
85+
```python
86+
from servicewright.adapters.observability._errors.sentry import SentryErrorTrackingSink
87+
88+
observability = ObservabilityManager(
89+
ObsConfig(error_tracking="sentry"),
90+
error_tracking=SentryErrorTrackingSink(ignore_errors=[DomainError]),
91+
)
92+
```
93+
94+
A `before_send` given this way is composed with the redactor, not replaced by it: it runs first,
95+
with the full `(event, hint)` — `hint["exc_info"]` for a captured exception,
96+
`hint["log_record"]` for one that arrived through the logging integration — and may return
97+
`None` to drop the event; whatever survives is redacted.
98+
99+
```python
100+
def keep(event: dict, hint: dict) -> dict | None:
101+
exc = hint.get("exc_info", (None, None, None))[1]
102+
return None if isinstance(exc, DomainError) else event
103+
104+
105+
SentryErrorTrackingSink(before_send=keep)
106+
```
107+
108+
Health probes are the other usual case. With Sentry performance on, kubelet's `livez` / `readyz`
109+
polling becomes a transaction every few seconds per pod; drop the `/system` namespace with
110+
`before_send_transaction` (or a `traces_sampler` returning `0` for it):
111+
112+
```python
113+
def drop_probes(event: dict, hint: dict) -> dict | None:
114+
return None if event.get("transaction", "").startswith("/system/") else event
115+
116+
117+
SentryErrorTrackingSink(before_send_transaction=drop_probes)
118+
```
119+
120+
`dsn`, `environment`, `release`, the sample rates and `debug` are settings-driven and the sink
121+
rejects them at construction, so a value cannot come from two places.
122+
78123
The reporting seam:
79124

80125
```python

‎docs/concepts/observability.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,13 @@ own `setup()` decides what to do with the settings.
9898

9999
```python
100100
ObservabilityManager(metrics=StatsdMetricsSink(host="127.0.0.1"))
101+
ObservabilityManager(error_tracking=SentryErrorTrackingSink(ignore_errors=[DomainError]))
101102
```
102103

104+
The built-in backends take their options the same way — `PrometheusMetricsSink(registry=...)`,
105+
`SentryErrorTrackingSink(**sentry_sdk_init_kwargs)` — so instance injection is how a backend is
106+
tuned beyond what the settings section models.
107+
103108
## Third-party backends
104109

105110
A backend is one module plus one registration. No kernel change:

‎servicewright/adapters/observability/_errors/sentry.py‎

Lines changed: 65 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
33
``setup()`` calls ``sentry_sdk.init`` (process-global, Host-owned); the
44
cross-cutting redactor from :class:`ObsSetupContext` is applied to every
5-
outgoing event via ``before_send``.
5+
outgoing event via ``before_send``. The settings section models only the
6+
deployment facts (DSN, environment, sampling); everything else
7+
``sentry_sdk.init`` accepts — ``ignore_errors``, a ``before_send`` that drops,
8+
``before_send_transaction``, ``traces_sampler``, ``integrations`` — is passed
9+
through the sink's constructor.
610
"""
711

812
from __future__ import annotations
@@ -18,13 +22,22 @@
1822
raise ImportError("Sentry error tracking requires servicewright[sentry]; install it.") from exc
1923

2024
if TYPE_CHECKING:
25+
from collections.abc import Callable
26+
2127
from ....core.contracts.observability import Redactor
2228
from ....core.observability.config import ObsSetupContext
2329

2430
logger = logging.getLogger(__name__)
2531

2632
_FLUSH_TIMEOUT_SECONDS = 2.0
2733

34+
# ``sentry_sdk.init`` arguments the sink derives from ``settings.error_tracking``
35+
# and the setup context; passing them to the constructor too would make two
36+
# sources of truth for one value, so they are rejected up front instead.
37+
_SETTINGS_DRIVEN_INIT_ARGS = frozenset(
38+
{"dsn", "environment", "release", "traces_sample_rate", "profiles_sample_rate", "debug"}
39+
)
40+
2841

2942
class SentryReporter:
3043
"""Thin :class:`ErrorReporterProtocol` seam over the global ``sentry_sdk``."""
@@ -50,11 +63,40 @@ def set_tags(self, **tags: str) -> None:
5063

5164

5265
class SentryErrorTrackingSink(ErrorTrackingSink):
53-
"""Sentry backend driven by ``settings.error_tracking``."""
66+
"""Sentry backend driven by ``settings.error_tracking``.
67+
68+
Args:
69+
**init_kwargs: Any further ``sentry_sdk.init`` argument the settings
70+
section does not model — ``ignore_errors``, ``before_send``,
71+
``before_send_transaction``, ``traces_sampler``, ``integrations``,
72+
``send_default_pii``, ... — used through instance injection::
73+
74+
ObservabilityManager(
75+
ObsConfig(error_tracking="sentry"),
76+
error_tracking=SentryErrorTrackingSink(ignore_errors=[DomainError]),
77+
)
78+
79+
The settings-driven arguments (``dsn``, ``environment``,
80+
``release``, the sample rates, ``debug``) stay the sink's business
81+
and are rejected here. A ``before_send`` given this way is composed
82+
with the redactor rather than replaced by it: it runs first, with
83+
the full ``(event, hint)``, and may return ``None`` to drop the
84+
event; whatever survives is redacted.
85+
86+
Raises:
87+
ValueError: If ``init_kwargs`` names a settings-driven argument.
88+
"""
5489

5590
backend = "sentry"
5691

57-
def __init__(self) -> None:
92+
def __init__(self, **init_kwargs: Any) -> None:
93+
clashing = sorted(_SETTINGS_DRIVEN_INIT_ARGS.intersection(init_kwargs))
94+
if clashing:
95+
raise ValueError(
96+
f"{', '.join(clashing)}: driven by settings.error_tracking and the setup context, "
97+
"not by SentryErrorTrackingSink arguments"
98+
)
99+
self._init_kwargs = init_kwargs
58100
self._initialized = False
59101

60102
def setup(self, ctx: ObsSetupContext) -> None:
@@ -65,14 +107,17 @@ def setup(self, ctx: ObsSetupContext) -> None:
65107
if sentry_settings is None or not getattr(sentry_settings, "dsn", None):
66108
return
67109

110+
init_kwargs = dict(self._init_kwargs)
111+
before_send = init_kwargs.pop("before_send", None)
68112
sentry_sdk.init(
113+
**init_kwargs,
69114
dsn=sentry_settings.dsn,
70115
environment=getattr(sentry_settings, "environment", "") or ctx.environment,
71116
release=ctx.app_version,
72117
traces_sample_rate=getattr(sentry_settings, "traces_sample_rate", 0.0),
73118
profiles_sample_rate=getattr(sentry_settings, "profiles_sample_rate", 0.0),
74119
debug=getattr(sentry_settings, "debug", False),
75-
before_send=_build_before_send(ctx.redactor),
120+
before_send=_build_before_send(ctx.redactor, before_send),
76121
)
77122
self._initialized = True
78123
logger.info("Sentry error tracking configured", extra={"environment": ctx.environment})
@@ -88,12 +133,24 @@ def reporter(self) -> SentryReporter:
88133
return SentryReporter()
89134

90135

91-
def _build_before_send(redactor: Redactor | None) -> Any:
92-
if redactor is None:
136+
def _build_before_send(redactor: Redactor | None, hook: Callable[..., Any] | None) -> Any:
137+
"""Compose the caller's ``before_send`` with the redactor.
138+
139+
The caller's hook decides *whether* an event is reported — it sees the
140+
``hint`` (``exc_info``, ``log_record``) and returns ``None`` to drop — and
141+
the redactor decides *what it may contain*, so it runs on whatever the hook
142+
lets through. Either side may be absent.
143+
"""
144+
if redactor is None and hook is None:
93145
return None
94146

95-
def before_send(event: dict[str, Any], hint: dict[str, Any]) -> dict[str, Any]:
96-
return redactor(event)
147+
def before_send(event: dict[str, Any], hint: dict[str, Any]) -> dict[str, Any] | None:
148+
if hook is not None:
149+
filtered = hook(event, hint)
150+
if filtered is None:
151+
return None
152+
event = filtered
153+
return redactor(event) if redactor is not None else event
97154

98155
return before_send
99156

‎tests/unit/test_observability_sinks.py‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,102 @@ def test__sentry_sink_setup__no_redactor__installs_no_before_send_hook(monkeypat
306306
assert init_calls[0]["before_send"] is None
307307

308308

309+
@pytest.fixture
310+
def sentry_init_calls(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
311+
"""Capture the kwargs of every ``sentry_sdk.init`` call instead of initializing the SDK."""
312+
calls: list[dict[str, Any]] = []
313+
monkeypatch.setattr(sentry_mod.sentry_sdk, "init", lambda **kwargs: calls.append(kwargs))
314+
return calls
315+
316+
317+
class _DomainError(Exception):
318+
"""An expected business error a service does not want reported."""
319+
320+
321+
def _drop_domain_errors(event: dict[str, Any], hint: dict[str, Any]) -> dict[str, Any] | None:
322+
exc_info = hint.get("exc_info")
323+
if exc_info is not None and isinstance(exc_info[1], _DomainError):
324+
return None
325+
return event
326+
327+
328+
def test__sentry_sink__init_kwargs_given__are_forwarded_next_to_the_settings_driven_ones(
329+
sentry_init_calls: list[dict[str, Any]],
330+
) -> None:
331+
# Arrange
332+
sink = SentryErrorTrackingSink(ignore_errors=[_DomainError], send_default_pii=False)
333+
334+
# Act
335+
sink.setup(_ctx(_settings_with(error_tracking=_SentrySettings())))
336+
337+
# Assert
338+
kwargs = sentry_init_calls[0]
339+
assert kwargs["ignore_errors"] == [_DomainError]
340+
assert kwargs["send_default_pii"] is False
341+
assert kwargs["dsn"] == "http://key@sentry.local/1"
342+
assert kwargs["release"] == "1.2.3"
343+
344+
345+
@pytest.mark.parametrize(
346+
"argument",
347+
["dsn", "environment", "release", "traces_sample_rate", "profiles_sample_rate", "debug"],
348+
)
349+
def test__sentry_sink__settings_driven_argument_given__raises_at_construction(argument: str) -> None:
350+
with pytest.raises(ValueError, match=f"{argument}: driven by settings.error_tracking"):
351+
SentryErrorTrackingSink(**{argument: "x"})
352+
353+
354+
def test__sentry_sink__before_send_given__runs_first_with_the_hint_and_may_drop(
355+
sentry_init_calls: list[dict[str, Any]],
356+
) -> None:
357+
# Arrange
358+
sink = SentryErrorTrackingSink(before_send=_drop_domain_errors)
359+
sink.setup(_ctx(_settings_with(error_tracking=_SentrySettings()), redactor=KeyRedactor()))
360+
before_send = sentry_init_calls[0]["before_send"]
361+
event = {"extra": {"password": "hunter2"}, "message": "x"}
362+
363+
# Act
364+
dropped = before_send(event, {"exc_info": (_DomainError, _DomainError("expected"), None)})
365+
kept = before_send(event, {"exc_info": (ValueError, ValueError("unexpected"), None)})
366+
367+
# Assert
368+
assert dropped is None
369+
assert kept is not None
370+
assert kept["extra"]["password"] == "[REDACTED]"
371+
372+
373+
def test__sentry_sink__before_send_given_without_a_redactor__is_installed_on_its_own(
374+
sentry_init_calls: list[dict[str, Any]],
375+
) -> None:
376+
# Arrange
377+
sink = SentryErrorTrackingSink(before_send=_drop_domain_errors)
378+
sink.setup(_ctx(_settings_with(error_tracking=_SentrySettings())))
379+
before_send = sentry_init_calls[0]["before_send"]
380+
event = {"extra": {"password": "hunter2"}}
381+
382+
# Act
383+
kept = before_send(event, {"exc_info": (ValueError, ValueError("unexpected"), None)})
384+
385+
# Assert
386+
assert kept == {"extra": {"password": "hunter2"}}
387+
388+
389+
def test__sentry_sink__before_send_transaction_given__is_forwarded_untouched(
390+
sentry_init_calls: list[dict[str, Any]],
391+
) -> None:
392+
# Arrange
393+
def drop_probes(event: dict[str, Any], hint: dict[str, Any]) -> dict[str, Any] | None:
394+
return None if str(event.get("transaction", "")).startswith("/system/") else event
395+
396+
sink = SentryErrorTrackingSink(before_send_transaction=drop_probes)
397+
398+
# Act
399+
sink.setup(_ctx(_settings_with(error_tracking=_SentrySettings()), redactor=KeyRedactor()))
400+
401+
# Assert
402+
assert sentry_init_calls[0]["before_send_transaction"] is drop_probes
403+
404+
309405
def test__sentry_reporter__error_reported__delegates_to_the_sdk(monkeypatch: pytest.MonkeyPatch) -> None:
310406
capture = MagicMock()
311407
breadcrumb = MagicMock()

0 commit comments

Comments
 (0)