observe-kit 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ """@observed: timing, outcome classification, structured logs and events for any call.
2
+
3
+ from observe_kit import observed
4
+
5
+ class Billing:
6
+ def __init__(self, log, sink): # Provider finds these by name
7
+ self.log, self.sink = log, sink
8
+
9
+ @observed("billing.charge", expected=(CardDeclined,), fields=("customer_id",))
10
+ def charge(self, customer_id: str, cents: int) -> Receipt: ...
11
+
12
+ Every call emits `billing.charge.finished` (or `.expected`, `.swallowed`, `.raised`) with
13
+ `duration_ms` and `customer_id`, as a structlog line and as an `ObservedEvent` to the sink.
14
+ """
15
+
16
+ from .decorator import observed
17
+ from .events import CallOutcome, ObservedEvent
18
+ from .policy import DEFAULT_POLICY, NotifyPolicy
19
+ from .provider import Provider
20
+ from .sinks import EventSink, MemorySink, Notifier, NullNotifier, NullSink
21
+ from .text import withhold_urls
22
+
23
+ __all__ = [
24
+ "DEFAULT_POLICY",
25
+ "CallOutcome",
26
+ "EventSink",
27
+ "MemorySink",
28
+ "Notifier",
29
+ "NotifyPolicy",
30
+ "NullNotifier",
31
+ "NullSink",
32
+ "ObservedEvent",
33
+ "Provider",
34
+ "observed",
35
+ "withhold_urls",
36
+ ]
@@ -0,0 +1,238 @@
1
+ """The `observed` decorator."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import time
7
+ from collections.abc import Awaitable, Callable, Mapping
8
+ from functools import wraps
9
+ from typing import Any, Literal, ParamSpec, TypeVar, cast
10
+
11
+ from .events import CallOutcome, ObservedEvent
12
+ from .policy import DEFAULT_POLICY, NotifyPolicy
13
+ from .provider import Provider
14
+
15
+ P = ParamSpec("P")
16
+ R = TypeVar("R")
17
+
18
+ ExcTypes = tuple[type[BaseException], ...]
19
+
20
+
21
+ def observed(
22
+ name: str,
23
+ *,
24
+ expected: ExcTypes = (),
25
+ swallow: ExcTypes = (),
26
+ default: Any = None,
27
+ fields: tuple[str, ...] = (),
28
+ detail: str | None = None,
29
+ level: Literal["debug", "info"] = "info",
30
+ notify_policy: NotifyPolicy = DEFAULT_POLICY,
31
+ ) -> Callable[[Callable[P, R]], Callable[P, R]]:
32
+ """Time a call, classify how it ended, log it and emit an event, on every invocation.
33
+
34
+ Args:
35
+ name: Event root, dotted, e.g. "billing.charge". The outcome is appended:
36
+ "billing.charge.finished".
37
+ expected: Exceptions that are a normal part of operating. Logged as a warning and
38
+ **re-raised** for the caller to handle.
39
+ swallow: Exceptions that mean "that thing wasn't there". Logged at debug and replaced by
40
+ `default`. This is how `except Exception: pass` becomes explicit and visible.
41
+ default: Returned when a `swallow` exception was caught.
42
+ fields: Argument names to add to the event and the log line, e.g. ("user_id",).
43
+ Resolved against the signature, so positional and keyword arguments both work.
44
+ detail: One argument name whose value, as a string, becomes the event's `detail`. It is
45
+ not added to the context: it is for a later query to read back, not for every log line.
46
+ level: Log level of the FINISHED outcome. "debug" for chatty inner calls.
47
+ notify_policy: What a RAISED notification may carry. The default allows no context
48
+ fields; see `NotifyPolicy`.
49
+
50
+ Anything that is an `Exception` and in neither tuple is RAISED: logged as an error with the
51
+ traceback, sent to the instance's notifier if it has one, and re-raised. A type in both
52
+ tuples counts as `expected`. `BaseException`s that are not `Exception`s (KeyboardInterrupt,
53
+ SystemExit, asyncio.CancelledError) pass through untouched unless listed.
54
+
55
+ Works on plain and `async def` functions and methods. Generators are refused, because the
56
+ call returns before the work happens and the timing would be meaningless.
57
+
58
+ Collaborators (logger, sink, notifier, context) come from the instance via `Provider`.
59
+ """
60
+
61
+ def decorate(func: Callable[P, R]) -> Callable[P, R]:
62
+ if inspect.isgeneratorfunction(func) or inspect.isasyncgenfunction(func):
63
+ raise TypeError(
64
+ f"@observed({name!r}) cannot wrap generator {func.__qualname__}: the call returns "
65
+ "before the work happens. Observe the function that consumes it instead."
66
+ )
67
+ spec = _Spec(
68
+ name=name,
69
+ expected=expected,
70
+ swallow=swallow,
71
+ default=default,
72
+ fields=fields,
73
+ detail=detail,
74
+ level=level,
75
+ policy=notify_policy,
76
+ sig=inspect.signature(func),
77
+ module=func.__module__,
78
+ qualname=f"{func.__module__}.{func.__qualname__}",
79
+ )
80
+
81
+ if inspect.iscoroutinefunction(func):
82
+
83
+ @wraps(func)
84
+ async def awrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
85
+ call = _Call(spec, args, kwargs)
86
+ try:
87
+ result = await cast(Awaitable[Any], func(*args, **kwargs))
88
+ except BaseException as exc:
89
+ if not call.failed(exc):
90
+ raise
91
+ return spec.default
92
+ call.finished()
93
+ return result
94
+
95
+ return cast(Callable[P, R], awrapper)
96
+
97
+ @wraps(func)
98
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
99
+ call = _Call(spec, args, kwargs)
100
+ try:
101
+ result = func(*args, **kwargs)
102
+ except BaseException as exc:
103
+ if not call.failed(exc):
104
+ raise
105
+ return cast(R, spec.default)
106
+ call.finished()
107
+ return result
108
+
109
+ return wrapper
110
+
111
+ return decorate
112
+
113
+
114
+ class _Spec:
115
+ """Everything fixed at decoration time."""
116
+
117
+ __slots__ = (
118
+ "name",
119
+ "expected",
120
+ "swallow",
121
+ "default",
122
+ "fields",
123
+ "detail",
124
+ "level",
125
+ "policy",
126
+ "sig",
127
+ "module",
128
+ "qualname",
129
+ )
130
+
131
+ def __init__(
132
+ self,
133
+ *,
134
+ name: str,
135
+ expected: ExcTypes,
136
+ swallow: ExcTypes,
137
+ default: Any,
138
+ fields: tuple[str, ...],
139
+ detail: str | None,
140
+ level: str,
141
+ policy: NotifyPolicy,
142
+ sig: inspect.Signature,
143
+ module: str,
144
+ qualname: str,
145
+ ) -> None:
146
+ self.name = name
147
+ self.expected = expected
148
+ self.swallow = swallow
149
+ self.default = default
150
+ self.fields = fields
151
+ self.detail = detail
152
+ self.level = level
153
+ self.policy = policy
154
+ self.sig = sig
155
+ self.module = module
156
+ self.qualname = qualname
157
+
158
+
159
+ class _Call:
160
+ """One invocation: collaborators resolved, clock started. Sync and async share it."""
161
+
162
+ __slots__ = ("spec", "args", "log", "sink", "context", "detail", "started")
163
+
164
+ def __init__(self, spec: _Spec, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
165
+ self.spec = spec
166
+ self.args = args
167
+ self.sink = Provider.sink(args)
168
+ bound = _bound(spec.sig, args, kwargs)
169
+ self.context = _context(spec.fields, Provider.context(args), bound)
170
+ self.detail = _detail(spec.detail, bound)
171
+ self.log = Provider.logger(args, spec.module).bind(**self.context)
172
+ self.started = time.perf_counter()
173
+
174
+ def finished(self) -> None:
175
+ ev = self._event(CallOutcome.FINISHED, None)
176
+ getattr(self.log, self.spec.level)(ev.event, duration_ms=ev.duration_ms)
177
+ self.sink.emit(ev)
178
+
179
+ def failed(self, exc: BaseException) -> bool:
180
+ """Record `exc`, from inside the `except` block. True when it is swallowed; the caller
181
+ re-raises otherwise, with a bare `raise`, so the traceback gains no frame from here."""
182
+ spec = self.spec
183
+ if isinstance(exc, spec.expected):
184
+ ev = self._event(CallOutcome.EXPECTED, exc)
185
+ self.log.warning(ev.event, duration_ms=ev.duration_ms, error=ev.error)
186
+ self.sink.emit(ev)
187
+ return False
188
+ if isinstance(exc, spec.swallow):
189
+ ev = self._event(CallOutcome.SWALLOWED, exc)
190
+ self.log.debug(
191
+ ev.event, duration_ms=ev.duration_ms, error=ev.error, default=spec.default
192
+ )
193
+ self.sink.emit(ev)
194
+ return True
195
+ if not isinstance(exc, Exception):
196
+ return False
197
+ ev = self._event(CallOutcome.RAISED, exc)
198
+ self.log.error(ev.event, duration_ms=ev.duration_ms, error=ev.error, exc_info=True)
199
+ self.sink.emit(ev)
200
+ notifier = Provider.notifier(self.args)
201
+ if notifier is not None:
202
+ notifier.error(
203
+ title=f"{spec.name} raised {type(exc).__name__}",
204
+ text=spec.policy.text(spec.qualname, ev.error, self.context),
205
+ )
206
+ return False
207
+
208
+ def _event(self, outcome: CallOutcome, exc: BaseException | None) -> ObservedEvent:
209
+ # perf_counter, then round: truncating to whole seconds first would report 0 ms for
210
+ # anything under a second.
211
+ duration_ms = round((time.perf_counter() - self.started) * 1000)
212
+ error = f"{type(exc).__name__}: {exc}" if exc is not None else None
213
+ return ObservedEvent(self.spec.name, outcome, duration_ms, error, self.context, self.detail)
214
+
215
+
216
+ def _bound(
217
+ sig: inspect.Signature, args: tuple[Any, ...], kwargs: dict[str, Any]
218
+ ) -> Mapping[str, Any]:
219
+ """The call's arguments by name, which `fields` and `detail` are resolved against."""
220
+ try:
221
+ return sig.bind_partial(*args, **kwargs).arguments
222
+ except TypeError: # the call itself is malformed; let func() raise the real error
223
+ return {}
224
+
225
+
226
+ def _context(
227
+ fields: tuple[str, ...], base: Mapping[str, object], bound: Mapping[str, Any]
228
+ ) -> dict[str, object]:
229
+ ctx: dict[str, object] = dict(base)
230
+ for f in fields:
231
+ if f in bound:
232
+ ctx[f] = bound[f]
233
+ return ctx
234
+
235
+
236
+ def _detail(name: str | None, bound: Mapping[str, Any]) -> str | None:
237
+ value = bound.get(name) if name is not None else None
238
+ return None if value is None else str(value)
observe_kit/events.py ADDED
@@ -0,0 +1,48 @@
1
+ """What one observed call produced."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from enum import StrEnum
8
+
9
+
10
+ class CallOutcome(StrEnum):
11
+ """How a call ended. Exactly one per call."""
12
+
13
+ FINISHED = "finished" # returned normally
14
+ EXPECTED = "expected" # listed in `expected`: warned, re-raised
15
+ SWALLOWED = "swallowed" # listed in `swallow`: debug-logged, `default` returned
16
+ RAISED = "raised" # any other Exception: error + traceback, notified, re-raised
17
+
18
+ @property
19
+ def level(self) -> str:
20
+ """The log level this outcome is written at (FINISHED's can be lowered per call)."""
21
+ return _LEVELS[self]
22
+
23
+
24
+ _LEVELS: dict[CallOutcome, str] = {
25
+ CallOutcome.FINISHED: "info",
26
+ CallOutcome.EXPECTED: "warning",
27
+ CallOutcome.SWALLOWED: "debug",
28
+ CallOutcome.RAISED: "error",
29
+ }
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class ObservedEvent:
34
+ """One call, as the sink receives it."""
35
+
36
+ name: str # the decorator's name, e.g. "billing.charge"
37
+ outcome: CallOutcome
38
+ duration_ms: int
39
+ error: str | None = None # "TypeName: message" when the call did not finish
40
+ context: Mapping[str, object] = field(default_factory=dict) # observe_context + `fields`
41
+ # The value of the argument `observed(detail=...)` names, as a string. For a call whose
42
+ # event a later query reads back, not for log lines: it is not part of `context`.
43
+ detail: str | None = None
44
+
45
+ @property
46
+ def event(self) -> str:
47
+ """The log event name: `<name>.<outcome>`."""
48
+ return f"{self.name}.{self.outcome}"
observe_kit/policy.py ADDED
@@ -0,0 +1,63 @@
1
+ """What a RAISED notification may carry.
2
+
3
+ A notification leaves the process: it lands on a phone, in a chat channel, in somebody's inbox.
4
+ The log line and the event keep the whole context and the whole error; the notification's job
5
+ is "something is wrong, come and look", and it carries only what the policy allows.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass
12
+
13
+ from .text import withhold_urls
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class NotifyPolicy:
18
+ """Which context fields travel, and how the error is cut down.
19
+
20
+ Args:
21
+ fields: Context names allowed into the message. An **allow**-list: `fields=` is chosen
22
+ per call site, so a deny-list would have to grow with every new argument, and
23
+ forgetting one would leak it. The default allows none.
24
+ withheld_hint: Where to find what was withheld, e.g. "see logs/app.jsonl". Appended to
25
+ the count of withheld fields.
26
+
27
+ The error is always cut to its first line, with URLs withheld (`withhold_urls`), and the
28
+ message says how many lines and fields it left out, so a policy that is too narrow shows up
29
+ as a number instead of as a call that seemed to have no context.
30
+ """
31
+
32
+ fields: frozenset[str] = frozenset()
33
+ withheld_hint: str = "see the log"
34
+
35
+ def context(self, context: Mapping[str, object]) -> str:
36
+ """The allowed `key=value` pairs, plus a count of the rest."""
37
+ kept = " ".join(f"{k}={v}" for k, v in context.items() if k in self.fields)
38
+ withheld = sum(1 for key in context if key not in self.fields)
39
+ if not withheld:
40
+ return kept
41
+ note = f"({withheld} field(s) withheld — {self.withheld_hint})"
42
+ return f"{kept} {note}" if kept else note
43
+
44
+ def error(self, error: str | None) -> str:
45
+ """The first line of the error with URLs withheld, plus a count of the dropped lines.
46
+
47
+ Only the first line, because libraries append their own detail below it (Playwright's
48
+ `Call log:`, a server's response body) and that is where identifiers tend to be. URLs are
49
+ taken out of the line that is kept, because some errors put them in the first line.
50
+ """
51
+ if not error:
52
+ return ""
53
+ first, _, rest = error.partition("\n")
54
+ line = withhold_urls(first).rstrip()
55
+ dropped = len(rest.splitlines()) if rest else 0
56
+ return f"{line} (+{dropped} line(s) withheld)" if dropped else line
57
+
58
+ def text(self, qualname: str, error: str | None, context: Mapping[str, object]) -> str:
59
+ """The notification body: where it raised, what it raised, the allowed context."""
60
+ return f"{qualname}\n{self.error(error)}\n{self.context(context)}"
61
+
62
+
63
+ DEFAULT_POLICY = NotifyPolicy()
@@ -0,0 +1,51 @@
1
+ """Find the collaborators `observed` needs on the decorated method's instance, or default.
2
+
3
+ Convention over wiring: if the object the method was called on has a `.log`, `.sink`,
4
+ `.notifier` or `.observe_context` of the right shape, it is used. Otherwise a module logger, no
5
+ sink, no notifier, no context. Plain functions always get the defaults.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from typing import Any
12
+
13
+ import structlog
14
+
15
+ from .sinks import EventSink, Notifier, NullSink
16
+
17
+
18
+ class Provider:
19
+ @staticmethod
20
+ def _self(args: tuple[Any, ...]) -> Any | None:
21
+ return args[0] if args else None
22
+
23
+ @staticmethod
24
+ def logger(args: tuple[Any, ...], default_name: str) -> Any:
25
+ """The instance's `.log` if it has a `bind` method, else a module structlog logger."""
26
+ log = getattr(Provider._self(args), "log", None)
27
+ if log is not None and callable(getattr(log, "bind", None)):
28
+ return log
29
+ return structlog.get_logger(default_name)
30
+
31
+ @staticmethod
32
+ def sink(args: tuple[Any, ...]) -> EventSink:
33
+ """The instance's `.sink` if it has an `emit` method, else a NullSink."""
34
+ sink = getattr(Provider._self(args), "sink", None)
35
+ if sink is not None and callable(getattr(sink, "emit", None)):
36
+ return sink # type: ignore[no-any-return]
37
+ return NullSink()
38
+
39
+ @staticmethod
40
+ def notifier(args: tuple[Any, ...]) -> Notifier | None:
41
+ """The instance's `.notifier` if it has an `error` method, else None."""
42
+ notifier = getattr(Provider._self(args), "notifier", None)
43
+ if notifier is not None and callable(getattr(notifier, "error", None)):
44
+ return notifier # type: ignore[no-any-return]
45
+ return None
46
+
47
+ @staticmethod
48
+ def context(args: tuple[Any, ...]) -> Mapping[str, object]:
49
+ """Fields bound to every event from this instance, e.g. {"run_id": ...}."""
50
+ ctx = getattr(Provider._self(args), "observe_context", None)
51
+ return ctx if isinstance(ctx, Mapping) else {}
observe_kit/py.typed ADDED
File without changes
observe_kit/sinks.py ADDED
@@ -0,0 +1,57 @@
1
+ """Where events go, and who is told when a call raises something unexpected.
2
+
3
+ Both are Protocols: anything with the right method satisfies them, without importing this
4
+ package.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Protocol, runtime_checkable
10
+
11
+ from .events import ObservedEvent
12
+
13
+
14
+ @runtime_checkable
15
+ class EventSink(Protocol):
16
+ """Receives every event: a metrics client, a database table, a queue, a list in a test."""
17
+
18
+ def emit(self, event: ObservedEvent) -> None: ...
19
+
20
+
21
+ @runtime_checkable
22
+ class Notifier(Protocol):
23
+ """Told about RAISED outcomes only: chat, e-mail, a pager.
24
+
25
+ `observed` calls `error(title=..., text=...)` by keyword. A notifier with a richer
26
+ signature (extra keyword-only arguments with defaults) still satisfies this.
27
+ """
28
+
29
+ def error(self, title: str, text: str) -> None: ...
30
+
31
+
32
+ class NullSink:
33
+ """Drops every event. What a call gets when its instance has no `.sink`."""
34
+
35
+ def emit(self, event: ObservedEvent) -> None:
36
+ return None
37
+
38
+
39
+ class NullNotifier:
40
+ """Tells nobody."""
41
+
42
+ def error(self, title: str, text: str) -> None:
43
+ return None
44
+
45
+
46
+ class MemorySink:
47
+ """Keeps every event in a list. For tests, and for inspecting a run afterwards."""
48
+
49
+ def __init__(self) -> None:
50
+ self.events: list[ObservedEvent] = []
51
+
52
+ def emit(self, event: ObservedEvent) -> None:
53
+ self.events.append(event)
54
+
55
+ def named(self, name: str) -> list[ObservedEvent]:
56
+ """The events of one decorated call, oldest first."""
57
+ return [e for e in self.events if e.name == name]
observe_kit/text.py ADDED
@@ -0,0 +1,19 @@
1
+ """Taking URLs out of a string before it leaves the process."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ URL_RE = re.compile(r"\bhttps?://\S+", re.IGNORECASE)
8
+ WITHHELD_URL = "<url withheld>"
9
+
10
+
11
+ def withhold_urls(text: str) -> str:
12
+ """Replace every URL-shaped run with `<url withheld>`, whole.
13
+
14
+ Deliberately blunt: a URL can carry an identifier, a signed query string or a token, and it
15
+ can come back truncated or re-encoded inside somebody else's error message, so it is not
16
+ matched against a known secret. A URL in a message a human reads adds nothing they could act
17
+ on anyway.
18
+ """
19
+ return URL_RE.sub(WITHHELD_URL, text)
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.5
2
+ Name: observe-kit
3
+ Version: 0.1.1
4
+ Summary: @observed: one decorator that times a call, classifies how it ended, logs it and emits an event.
5
+ Project-URL: Homepage, https://github.com/MdaaaaO/observe-kit
6
+ Project-URL: Changelog, https://github.com/MdaaaaO/observe-kit/blob/main/CHANGELOG.md
7
+ Project-URL: Issues, https://github.com/MdaaaaO/observe-kit/issues
8
+ Author: Georg Kasper
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Keywords: decorator,events,logging,metrics,observability,structlog
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: System :: Logging
22
+ Classifier: Topic :: System :: Monitoring
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: structlog>=24.1
26
+ Description-Content-Type: text/markdown
27
+
28
+ # observe-kit
29
+
30
+ [![PyPI](https://img.shields.io/pypi/v/observe-kit)](https://pypi.org/project/observe-kit/)
31
+ [![Python](https://img.shields.io/pypi/pyversions/observe-kit)](https://pypi.org/project/observe-kit/)
32
+ [![CI](https://github.com/MdaaaaO/observe-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/MdaaaaO/observe-kit/actions/workflows/ci.yml)
33
+ [![Coverage](https://raw.githubusercontent.com/MdaaaaO/observe-kit/python-coverage-comment-action-data/badge.svg)](https://github.com/MdaaaaO/observe-kit/tree/python-coverage-comment-action-data)
34
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
35
+ [![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen)](CONTRIBUTING.md)
36
+
37
+ One decorator, `@observed`, that times a call, decides how it ended, writes a
38
+ [structlog](https://www.structlog.org) line and emits an event to a sink you choose. It works on
39
+ plain and `async def` functions and methods. Its only dependency is structlog.
40
+
41
+ ```console
42
+ pip install observe-kit
43
+ ```
44
+
45
+ ```python
46
+ from observe_kit import observed
47
+
48
+
49
+ class Billing:
50
+ def __init__(self, log, sink, notifier):
51
+ self.log, self.sink, self.notifier = log, sink, notifier
52
+
53
+ @observed("billing.charge", expected=(CardDeclined,), fields=("customer_id",))
54
+ def charge(self, customer_id: str, cents: int) -> Receipt: ...
55
+ ```
56
+
57
+ Each call to `charge` then produces one log line and one event:
58
+
59
+ ```text
60
+ billing.charge.finished customer_id=c_42 duration_ms=183
61
+ billing.charge.expected customer_id=c_42 duration_ms=95 error="CardDeclined: insufficient funds"
62
+ ```
63
+
64
+ ## Four outcomes
65
+
66
+ Every call ends in exactly one of them. You decide which exceptions are which, so there is no
67
+ bare `except Exception: pass` anywhere in your code.
68
+
69
+ | outcome | when | logged at | then |
70
+ |---|---|---|---|
71
+ | `finished` | the call returned | info (`level="debug"` for chatty calls) | the value is returned |
72
+ | `expected` | raised one of `expected=` | warning | re-raised for the caller |
73
+ | `swallowed` | raised one of `swallow=` | debug | `default=` is returned |
74
+ | `raised` | raised any other `Exception` | error, with traceback | the notifier is told, then re-raised |
75
+
76
+ A type listed in both `expected` and `swallow` counts as expected. `BaseException`s that are not
77
+ `Exception`s (`KeyboardInterrupt`, `SystemExit`, `asyncio.CancelledError`) pass through untouched
78
+ unless you list them. The re-raise is a bare `raise`, so tracebacks gain no frame from the decorator.
79
+
80
+ ## Arguments
81
+
82
+ ```python
83
+ @observed(
84
+ "orders.ship", # event root; the outcome is appended: orders.ship.finished
85
+ expected=(OutOfStock,), # normal operation, re-raised
86
+ swallow=(KeyError,), # "it wasn't there", replaced by default
87
+ default=None,
88
+ fields=("order_id",), # argument names added to the log line and the event
89
+ detail="carrier", # one argument kept as a string on the event, not in the log context
90
+ level="info", # log level of `finished`
91
+ notify_policy=POLICY, # what a `raised` notification may carry (below)
92
+ )
93
+ ```
94
+
95
+ `fields` and `detail` are resolved against the signature, so positional and keyword arguments both
96
+ work. `duration_ms` is measured with `perf_counter` and, for `async def`, covers the whole await.
97
+ Generators are refused at decoration time: the call returns before any work happens, so the timing
98
+ would mean nothing. Decorate the function that consumes the generator instead.
99
+
100
+ ## Where the logger, sink and notifier come from
101
+
102
+ `observed` looks at the first argument (`self` for a method) for these attributes, and falls back
103
+ to a default when one is missing or has the wrong shape:
104
+
105
+ | attribute | expected shape | fallback |
106
+ |---|---|---|
107
+ | `log` | a structlog logger (has `.bind`) | `structlog.get_logger(module)` |
108
+ | `sink` | an `EventSink`: `emit(event)` | `NullSink`, which drops events |
109
+ | `notifier` | a `Notifier`: `error(title, text)` | none; nobody is told |
110
+ | `observe_context` | a mapping, e.g. `{"run_id": 7}` | `{}` |
111
+
112
+ `observe_context` is bound onto every log line and event from that instance. Plain functions get
113
+ the fallbacks, so `@observed` on a module-level function just logs.
114
+
115
+ ## Events and sinks
116
+
117
+ Each outcome becomes an `ObservedEvent`:
118
+
119
+ ```python
120
+ ObservedEvent(
121
+ name="billing.charge",
122
+ outcome=CallOutcome.EXPECTED,
123
+ duration_ms=95,
124
+ error="CardDeclined: insufficient funds", # None when finished
125
+ context={"customer_id": "c_42"},
126
+ detail=None,
127
+ )
128
+ event.event # "billing.charge.expected"
129
+ ```
130
+
131
+ A sink is anything with `emit(event)`. Write one that increments a Prometheus counter, inserts a
132
+ row into a table, or pushes to a queue:
133
+
134
+ ```python
135
+ class CountingSink:
136
+ def __init__(self, counter):
137
+ self.counter = counter
138
+
139
+ def emit(self, event):
140
+ self.counter.labels(event.name, event.outcome).inc()
141
+ ```
142
+
143
+ ## Testing with MemorySink
144
+
145
+ `MemorySink` keeps every event in a list, so tests assert on what happened instead of parsing logs:
146
+
147
+ ```python
148
+ from observe_kit import CallOutcome, MemorySink
149
+
150
+
151
+ def test_declined_card_is_expected():
152
+ sink = MemorySink()
153
+ billing = Billing(log=structlog.get_logger(), sink=sink, notifier=None)
154
+
155
+ with pytest.raises(CardDeclined):
156
+ billing.charge("c_42", 500)
157
+
158
+ [event] = sink.named("billing.charge")
159
+ assert event.outcome is CallOutcome.EXPECTED
160
+ ```
161
+
162
+ ## Notifications and NotifyPolicy
163
+
164
+ On `raised`, the instance's notifier gets a title (`"billing.charge raised TimeoutError"`) and a
165
+ short text. Alerts end up in chat apps, phones and mailboxes, so the text is deliberately thin:
166
+
167
+ - only context fields you allow travel; the rest are counted, never shown;
168
+ - only the first line of the error travels; the lines after it are counted;
169
+ - URLs in that line are replaced by `<url withheld>`.
170
+
171
+ The default policy allows no fields. Set your own once and pass it where you decorate:
172
+
173
+ ```python
174
+ from functools import partial
175
+ from observe_kit import NotifyPolicy, observed as _observed
176
+
177
+ POLICY = NotifyPolicy(
178
+ fields=frozenset({"run_id", "count", "duration_ms"}),
179
+ withheld_hint="see logs/app.jsonl",
180
+ )
181
+ observed = partial(_observed, notify_policy=POLICY)
182
+ ```
183
+
184
+ ```text
185
+ billing.charge raised TimeoutError
186
+
187
+ app.billing.Billing.charge
188
+ TimeoutError: Page.goto: Timeout 30000ms exceeded. (+2 line(s) withheld)
189
+ run_id=7 (1 field(s) withheld — see logs/app.jsonl)
190
+ ```
191
+
192
+ The full error, traceback and context are still in the log line and the event; only the
193
+ notification is trimmed.
194
+
195
+ ## Lineage
196
+
197
+ observe-kit is a rewrite of [atlassian-labs/observe](https://github.com/atlassian-labs/observe),
198
+ which I wrote at Atlassian in 2020. It keeps the idea and the Apache-2.0 license; the code is new.
199
+ See [NOTICE](NOTICE).
200
+
201
+ ## License
202
+
203
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,13 @@
1
+ observe_kit/__init__.py,sha256=0CnbLiWeRzAjUpHUF7oZbgr6LZugrEUifkDCf9U3ftc,1118
2
+ observe_kit/decorator.py,sha256=dYU_yqVN4Kj6pYIVExGcXvgxY9pWPUYb_0lWfitFDr0,8791
3
+ observe_kit/events.py,sha256=4D9mPtWjPp0A9RgdZ6rDdSMzFJsUX4pMJVe3mEuh3ak,1627
4
+ observe_kit/policy.py,sha256=d0gBO5SHhzxo1PilZ1-T2L1J9OCAseigguwxRbVGX-0,2794
5
+ observe_kit/provider.py,sha256=shbRaG6DW28Wi6HeNbHBIiPF6q-YjYIV3p3xIY7IDcA,2060
6
+ observe_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ observe_kit/sinks.py,sha256=Gc68aIdRxMzGVTSovPNLjzS-IWzoBB7CesnJq3R12mw,1577
8
+ observe_kit/text.py,sha256=KTgxUSQH9vqvwH9VDe-top-YVe6ouDEvomvMqAnX0Dk,655
9
+ observe_kit-0.1.1.dist-info/METADATA,sha256=beVrslfyE4J6TKJuY8JHvCOJdRcOVFXz-BmRbFLnFBc,7839
10
+ observe_kit-0.1.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
11
+ observe_kit-0.1.1.dist-info/licenses/LICENSE,sha256=515cJROAdHB0IS3GKEE3DdY4OH_Jh-ogd1Cbc_eB2NI,11343
12
+ observe_kit-0.1.1.dist-info/licenses/NOTICE,sha256=1eAA_MXNRwflnCtFs6uLhSHphH8XX2X1ySAMlCRYRcg,606
13
+ observe_kit-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Georg Kasper
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,11 @@
1
+ observe-kit
2
+ Copyright 2026 Georg Kasper
3
+
4
+ This product is a rewrite of "observe" (https://github.com/atlassian-labs/observe),
5
+ Copyright [2020] Atlassian Pty Ltd, licensed under the Apache License, Version 2.0.
6
+ Georg Kasper was the author of that project.
7
+
8
+ Changes from the original: new code base built around a single `observed` decorator with four
9
+ explicit outcomes (finished, expected, swallowed, raised); structlog logging; pluggable event
10
+ sinks and notifiers found on the decorated instance; async support; and a notification policy
11
+ that keeps context fields, extra error lines and URLs out of alerts.