otelstarter 0.1.0__tar.gz
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.
- otelstarter-0.1.0/.gitignore +15 -0
- otelstarter-0.1.0/LICENSE +202 -0
- otelstarter-0.1.0/PKG-INFO +76 -0
- otelstarter-0.1.0/README.md +60 -0
- otelstarter-0.1.0/RELEASING.md +44 -0
- otelstarter-0.1.0/pyproject.toml +46 -0
- otelstarter-0.1.0/src/otelstarter/__init__.py +11 -0
- otelstarter-0.1.0/src/otelstarter/observability.py +144 -0
- otelstarter-0.1.0/src/otelstarter/py.typed +0 -0
- otelstarter-0.1.0/tests/conftest.py +46 -0
- otelstarter-0.1.0/tests/test_observability.py +137 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: otelstarter
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Business-aware domain events for OpenTelemetry, from the otelstarter project.
|
|
5
|
+
Project-URL: Homepage, https://github.com/IvyMurage/otelstarter
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: opentelemetry-api>=1.45.0
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: mypy>=1.11; extra == 'dev'
|
|
12
|
+
Requires-Dist: opentelemetry-sdk==1.45.0; extra == 'dev'
|
|
13
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
14
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# otelstarter (Python)
|
|
18
|
+
|
|
19
|
+
Business-aware domain events for OpenTelemetry. Part of [otelstarter](https://github.com/IvyMurage/otelstarter).
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from otelstarter import observability
|
|
23
|
+
|
|
24
|
+
observability.event(
|
|
25
|
+
"payment.completed",
|
|
26
|
+
domain="payments",
|
|
27
|
+
operation="payment",
|
|
28
|
+
outcome="success",
|
|
29
|
+
entity_type="payment",
|
|
30
|
+
entity_id=payment.id,
|
|
31
|
+
)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Each call emits **one OpenTelemetry log-based event**: a log record whose event name is `payment.completed`, linked to the current trace. OpenTelemetry adds the trace and span IDs, service name and environment itself.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
The package is not on PyPI yet. Install it from GitHub:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install "otelstarter @ git+https://github.com/IvyMurage/otelstarter#subdirectory=sdk/python"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
It depends only on `opentelemetry-api`. Run your app with OpenTelemetry configured (for example via `otelstarter run -- <your command>`), or `event()` quietly does nothing.
|
|
45
|
+
|
|
46
|
+
## Rules it enforces
|
|
47
|
+
|
|
48
|
+
- **Business meaning, not payloads.** Only the named fields above exist, with values that are short strings or ints. Anything else is left out with a warning.
|
|
49
|
+
- **`<domain>.<action>` names**, in lowercase, such as `order.created` or `payment.authorization.failed`. A name that breaks the rule is still recorded, with a one-time `OtelStarterWarning`.
|
|
50
|
+
- **Never breaks your app.** `event()` never raises. Internal errors become a one-time `OtelStarterWarning`.
|
|
51
|
+
- **One signal per event.** No duplicate span event or log line, and no automatic metric, so `entity_id` never becomes a metric label.
|
|
52
|
+
|
|
53
|
+
## Finding events in Grafana
|
|
54
|
+
|
|
55
|
+
With `otelstarter run`, open Grafana → Explore → Loki:
|
|
56
|
+
|
|
57
|
+
```text
|
|
58
|
+
{service_name="shop"} |= "payment." # all payment events
|
|
59
|
+
{service_name="shop"} | event_domain="payments" # by domain
|
|
60
|
+
{service_name="shop"} | event_outcome="failure" # failures only
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Each event carries `trace_id`, so you can jump from it to the request's trace in Tempo. Loki does not store OpenTelemetry's event-name field, which is why the event name is also the log body.
|
|
64
|
+
|
|
65
|
+
See [docs/DOMAIN_EVENTS.md](https://github.com/IvyMurage/otelstarter/blob/main/docs/DOMAIN_EVENTS.md) for the event model.
|
|
66
|
+
|
|
67
|
+
## Development
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
cd sdk/python
|
|
71
|
+
python -m venv .venv && . .venv/bin/activate
|
|
72
|
+
pip install -e '.[dev]'
|
|
73
|
+
pytest
|
|
74
|
+
ruff check . && ruff format --check .
|
|
75
|
+
mypy
|
|
76
|
+
```
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# otelstarter (Python)
|
|
2
|
+
|
|
3
|
+
Business-aware domain events for OpenTelemetry. Part of [otelstarter](https://github.com/IvyMurage/otelstarter).
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from otelstarter import observability
|
|
7
|
+
|
|
8
|
+
observability.event(
|
|
9
|
+
"payment.completed",
|
|
10
|
+
domain="payments",
|
|
11
|
+
operation="payment",
|
|
12
|
+
outcome="success",
|
|
13
|
+
entity_type="payment",
|
|
14
|
+
entity_id=payment.id,
|
|
15
|
+
)
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Each call emits **one OpenTelemetry log-based event**: a log record whose event name is `payment.completed`, linked to the current trace. OpenTelemetry adds the trace and span IDs, service name and environment itself.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
The package is not on PyPI yet. Install it from GitHub:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install "otelstarter @ git+https://github.com/IvyMurage/otelstarter#subdirectory=sdk/python"
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
It depends only on `opentelemetry-api`. Run your app with OpenTelemetry configured (for example via `otelstarter run -- <your command>`), or `event()` quietly does nothing.
|
|
29
|
+
|
|
30
|
+
## Rules it enforces
|
|
31
|
+
|
|
32
|
+
- **Business meaning, not payloads.** Only the named fields above exist, with values that are short strings or ints. Anything else is left out with a warning.
|
|
33
|
+
- **`<domain>.<action>` names**, in lowercase, such as `order.created` or `payment.authorization.failed`. A name that breaks the rule is still recorded, with a one-time `OtelStarterWarning`.
|
|
34
|
+
- **Never breaks your app.** `event()` never raises. Internal errors become a one-time `OtelStarterWarning`.
|
|
35
|
+
- **One signal per event.** No duplicate span event or log line, and no automatic metric, so `entity_id` never becomes a metric label.
|
|
36
|
+
|
|
37
|
+
## Finding events in Grafana
|
|
38
|
+
|
|
39
|
+
With `otelstarter run`, open Grafana → Explore → Loki:
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
{service_name="shop"} |= "payment." # all payment events
|
|
43
|
+
{service_name="shop"} | event_domain="payments" # by domain
|
|
44
|
+
{service_name="shop"} | event_outcome="failure" # failures only
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Each event carries `trace_id`, so you can jump from it to the request's trace in Tempo. Loki does not store OpenTelemetry's event-name field, which is why the event name is also the log body.
|
|
48
|
+
|
|
49
|
+
See [docs/DOMAIN_EVENTS.md](https://github.com/IvyMurage/otelstarter/blob/main/docs/DOMAIN_EVENTS.md) for the event model.
|
|
50
|
+
|
|
51
|
+
## Development
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
cd sdk/python
|
|
55
|
+
python -m venv .venv && . .venv/bin/activate
|
|
56
|
+
pip install -e '.[dev]'
|
|
57
|
+
pytest
|
|
58
|
+
ruff check . && ruff format --check .
|
|
59
|
+
mypy
|
|
60
|
+
```
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Releasing the Python SDK
|
|
2
|
+
|
|
3
|
+
The `Release Python SDK` workflow (`.github/workflows/release-python-sdk.yml`) publishes `sdk/python` to PyPI when a tag like `sdk-python-v0.1.0` is pushed. It uses PyPI **Trusted Publishing**: PyPI trusts the workflow's GitHub identity, so no API token is stored anywhere.
|
|
4
|
+
|
|
5
|
+
## One-time setup
|
|
6
|
+
|
|
7
|
+
**On PyPI**, signed in as the maintainer:
|
|
8
|
+
|
|
9
|
+
1. Open your account menu, then **Publishing**.
|
|
10
|
+
2. Add a new **pending publisher** for **GitHub Actions** with:
|
|
11
|
+
|
|
12
|
+
| Field | Value |
|
|
13
|
+
|-------|-------|
|
|
14
|
+
| PyPI project name | `otelstarter` |
|
|
15
|
+
| Repository | `IvyMurage/otelstarter` |
|
|
16
|
+
| Workflow file name | `release-python-sdk.yml` |
|
|
17
|
+
| Environment name | `pypi` |
|
|
18
|
+
|
|
19
|
+
A pending publisher does not reserve the name. If someone else registers `otelstarter` before the first release, the pending publisher stops working, so publish soon after setting it up.
|
|
20
|
+
|
|
21
|
+
**On GitHub**, in the repository's **Settings → Environments**:
|
|
22
|
+
|
|
23
|
+
1. Create an environment named `pypi`.
|
|
24
|
+
2. Optionally add yourself as a **required reviewer**. Every release then waits for you to click *Approve* before anything is uploaded.
|
|
25
|
+
|
|
26
|
+
## Each release
|
|
27
|
+
|
|
28
|
+
1. Set the new version in `src/otelstarter/__init__.py`. It is the only place the version lives.
|
|
29
|
+
2. Add the release to `CHANGELOG.md`.
|
|
30
|
+
3. Merge to `main`, then tag that commit and push the tag:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
git tag sdk-python-v0.1.0
|
|
34
|
+
git push origin sdk-python-v0.1.0
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The workflow then:
|
|
38
|
+
|
|
39
|
+
1. checks that the tag matches the version, and stops if it doesn't
|
|
40
|
+
2. runs the tests
|
|
41
|
+
3. builds and checks the package
|
|
42
|
+
4. publishes it
|
|
43
|
+
|
|
44
|
+
A version cannot be uploaded to PyPI twice, so a mistake needs a new version number.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "otelstarter"
|
|
7
|
+
dynamic = ["version"] # read from src/otelstarter/__init__.py, the single source
|
|
8
|
+
description = "Business-aware domain events for OpenTelemetry, from the otelstarter project."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
# Only the API: an app without OpenTelemetry configured gets a no-op, and the
|
|
13
|
+
# app chooses the SDK version. 1.45.0 is the version otelstarter tests with.
|
|
14
|
+
dependencies = ["opentelemetry-api>=1.45.0"]
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
dev = [
|
|
18
|
+
"opentelemetry-sdk==1.45.0",
|
|
19
|
+
"pytest>=8",
|
|
20
|
+
"ruff>=0.6",
|
|
21
|
+
"mypy>=1.11",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/IvyMurage/otelstarter"
|
|
26
|
+
|
|
27
|
+
[tool.hatch.version]
|
|
28
|
+
path = "src/otelstarter/__init__.py"
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/otelstarter"]
|
|
32
|
+
|
|
33
|
+
[tool.ruff]
|
|
34
|
+
line-length = 120
|
|
35
|
+
target-version = "py310"
|
|
36
|
+
|
|
37
|
+
[tool.ruff.lint]
|
|
38
|
+
select = ["E", "F", "W", "I", "B", "UP", "BLE"]
|
|
39
|
+
|
|
40
|
+
[tool.mypy]
|
|
41
|
+
strict = true
|
|
42
|
+
files = ["src"]
|
|
43
|
+
|
|
44
|
+
[tool.pytest.ini_options]
|
|
45
|
+
testpaths = ["tests"]
|
|
46
|
+
filterwarnings = ["error"] # unexpected warnings fail the tests
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""otelstarter: business-aware domain events on top of OpenTelemetry.
|
|
2
|
+
|
|
3
|
+
from otelstarter import observability
|
|
4
|
+
|
|
5
|
+
observability.event("order.created", domain="orders", outcome="success")
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from otelstarter import observability
|
|
9
|
+
|
|
10
|
+
__all__ = ["observability"]
|
|
11
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Record business events alongside your app's OpenTelemetry telemetry.
|
|
2
|
+
|
|
3
|
+
from otelstarter import observability
|
|
4
|
+
|
|
5
|
+
observability.event("payment.completed", domain="payments", outcome="success")
|
|
6
|
+
|
|
7
|
+
Each call emits one OpenTelemetry log-based event: a log record whose event
|
|
8
|
+
name is the event, linked to the current trace. OpenTelemetry adds the
|
|
9
|
+
technical context (trace and span IDs, service name, environment) itself.
|
|
10
|
+
|
|
11
|
+
Recording an event never raises, so observability can never break the app.
|
|
12
|
+
Problems are reported once each through Python's warnings module.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
import warnings
|
|
19
|
+
|
|
20
|
+
from opentelemetry._logs import SeverityNumber, get_logger
|
|
21
|
+
|
|
22
|
+
__all__ = ["OtelStarterWarning", "event"]
|
|
23
|
+
|
|
24
|
+
# <domain>.<action>, lowercase: "payment.completed", "payment.authorization.failed".
|
|
25
|
+
_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$")
|
|
26
|
+
|
|
27
|
+
# Longer values look like payloads, not business meaning.
|
|
28
|
+
_MAX_VALUE_LENGTH = 256
|
|
29
|
+
|
|
30
|
+
# A proxy logger: it starts sending once the app configures OpenTelemetry
|
|
31
|
+
# (for example via opentelemetry-instrument) and does nothing before that.
|
|
32
|
+
_logger = get_logger("otelstarter")
|
|
33
|
+
|
|
34
|
+
_warned: set[str] = set()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class OtelStarterWarning(UserWarning):
|
|
38
|
+
"""Warns about a domain event that was recorded imperfectly or not at all.
|
|
39
|
+
|
|
40
|
+
Filter it like any warning, for example to fail tests on it:
|
|
41
|
+
``warnings.simplefilter("error", OtelStarterWarning)``.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def event(
|
|
46
|
+
name: str,
|
|
47
|
+
*,
|
|
48
|
+
domain: str | None = None,
|
|
49
|
+
operation: str | None = None,
|
|
50
|
+
outcome: str | None = None,
|
|
51
|
+
entity_type: str | None = None,
|
|
52
|
+
entity_id: str | int | None = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
"""Record that something meaningful happened in the business.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
name: What happened, as ``<domain>.<action>``, for example
|
|
58
|
+
``"payment.completed"``. The only required argument.
|
|
59
|
+
domain: The business capability, for example ``"payments"``.
|
|
60
|
+
operation: The business activity, for example ``"payment"``.
|
|
61
|
+
outcome: Preferably ``"success"``, ``"failure"``, ``"cancelled"``
|
|
62
|
+
or ``"rejected"``.
|
|
63
|
+
entity_type: The business object involved, for example ``"order"``.
|
|
64
|
+
entity_id: Its identifier. Recorded on the event only; otelstarter
|
|
65
|
+
never turns it into a metric label.
|
|
66
|
+
|
|
67
|
+
There is deliberately no way to attach other data: events carry business
|
|
68
|
+
meaning, not business payloads.
|
|
69
|
+
"""
|
|
70
|
+
try:
|
|
71
|
+
_emit(name, domain, operation, outcome, entity_type, entity_id)
|
|
72
|
+
except Exception as exc: # noqa: BLE001 - recording must never break the app
|
|
73
|
+
_warn_once("emit-failed", f"otelstarter could not record event {name!r}: {exc!r}")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _emit(
|
|
77
|
+
name: object,
|
|
78
|
+
domain: object,
|
|
79
|
+
operation: object,
|
|
80
|
+
outcome: object,
|
|
81
|
+
entity_type: object,
|
|
82
|
+
entity_id: object,
|
|
83
|
+
) -> None:
|
|
84
|
+
if not isinstance(name, str) or not name:
|
|
85
|
+
_warn_once("name-type", f"Event name must be a non-empty string, got {name!r}. The event was not recorded.")
|
|
86
|
+
return
|
|
87
|
+
if not _NAME_PATTERN.match(name):
|
|
88
|
+
_warn_once(
|
|
89
|
+
"name:" + name,
|
|
90
|
+
f"Event name {name!r} does not follow <domain>.<action> in lowercase, "
|
|
91
|
+
"for example 'payment.completed'. The event was still recorded.",
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
fields = {
|
|
95
|
+
"event.domain": domain,
|
|
96
|
+
"event.outcome": outcome,
|
|
97
|
+
"business.operation": operation,
|
|
98
|
+
"business.entity.type": entity_type,
|
|
99
|
+
"business.entity.id": entity_id,
|
|
100
|
+
}
|
|
101
|
+
attributes: dict[str, str] = {}
|
|
102
|
+
for key, value in fields.items():
|
|
103
|
+
cleaned = _clean(name, key, value)
|
|
104
|
+
if cleaned is not None:
|
|
105
|
+
attributes[key] = cleaned
|
|
106
|
+
|
|
107
|
+
_logger.emit(
|
|
108
|
+
event_name=name,
|
|
109
|
+
body=name, # so log views that show only the body still show the event
|
|
110
|
+
severity_number=SeverityNumber.INFO,
|
|
111
|
+
severity_text="INFO",
|
|
112
|
+
attributes=attributes,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _clean(name: str, key: str, value: object) -> str | None:
|
|
117
|
+
"""Return the value as a short string, or None to leave the field out."""
|
|
118
|
+
if value is None:
|
|
119
|
+
return None
|
|
120
|
+
# bool is a subclass of int, so rule it out explicitly.
|
|
121
|
+
if isinstance(value, bool) or not isinstance(value, (str, int)):
|
|
122
|
+
_warn_once(
|
|
123
|
+
f"type:{key}",
|
|
124
|
+
f"{key} on event {name!r} must be a string or int, got {type(value).__name__}. "
|
|
125
|
+
"It was left out: events carry business meaning, not payloads.",
|
|
126
|
+
)
|
|
127
|
+
return None
|
|
128
|
+
text = str(value)
|
|
129
|
+
if len(text) > _MAX_VALUE_LENGTH:
|
|
130
|
+
_warn_once(
|
|
131
|
+
f"long:{key}",
|
|
132
|
+
f"{key} on event {name!r} is {len(text)} characters long, which looks like a payload. "
|
|
133
|
+
f"It was cut to {_MAX_VALUE_LENGTH}.",
|
|
134
|
+
)
|
|
135
|
+
text = text[:_MAX_VALUE_LENGTH]
|
|
136
|
+
return text
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _warn_once(key: str, message: str) -> None:
|
|
140
|
+
if key in _warned:
|
|
141
|
+
return
|
|
142
|
+
_warned.add(key)
|
|
143
|
+
# stacklevel=4 points the warning at the user's event() call.
|
|
144
|
+
warnings.warn(message, OtelStarterWarning, stacklevel=4)
|
|
File without changes
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Configure an in-memory OpenTelemetry SDK once for the whole test run.
|
|
2
|
+
|
|
3
|
+
OpenTelemetry allows the global providers to be set only once per process,
|
|
4
|
+
so each test clears the exporters instead of creating new providers.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
from opentelemetry import trace
|
|
13
|
+
from opentelemetry._logs import set_logger_provider
|
|
14
|
+
from opentelemetry.sdk._logs import LoggerProvider
|
|
15
|
+
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor
|
|
16
|
+
from opentelemetry.sdk.resources import Resource
|
|
17
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
18
|
+
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
19
|
+
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
|
20
|
+
|
|
21
|
+
from otelstarter import observability
|
|
22
|
+
|
|
23
|
+
RESOURCE = Resource.create({"service.name": "shop", "deployment.environment.name": "test"})
|
|
24
|
+
|
|
25
|
+
_logs = InMemoryLogRecordExporter()
|
|
26
|
+
_log_provider = LoggerProvider(resource=RESOURCE)
|
|
27
|
+
_log_provider.add_log_record_processor(SimpleLogRecordProcessor(_logs))
|
|
28
|
+
set_logger_provider(_log_provider)
|
|
29
|
+
|
|
30
|
+
_spans = InMemorySpanExporter()
|
|
31
|
+
_tracer_provider = TracerProvider(resource=RESOURCE)
|
|
32
|
+
_tracer_provider.add_span_processor(SimpleSpanProcessor(_spans))
|
|
33
|
+
trace.set_tracer_provider(_tracer_provider)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@pytest.fixture
|
|
37
|
+
def logs() -> Iterator[InMemoryLogRecordExporter]:
|
|
38
|
+
_logs.clear()
|
|
39
|
+
observability._warned.clear() # each test sees warnings afresh
|
|
40
|
+
yield _logs
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@pytest.fixture
|
|
44
|
+
def spans() -> Iterator[InMemorySpanExporter]:
|
|
45
|
+
_spans.clear()
|
|
46
|
+
yield _spans
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
import warnings
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from opentelemetry import trace
|
|
9
|
+
from opentelemetry._logs import SeverityNumber
|
|
10
|
+
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter
|
|
11
|
+
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
|
12
|
+
|
|
13
|
+
from otelstarter import observability
|
|
14
|
+
from otelstarter.observability import OtelStarterWarning
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def only_record(logs: InMemoryLogRecordExporter): # type: ignore[no-untyped-def]
|
|
18
|
+
finished = logs.get_finished_logs()
|
|
19
|
+
assert len(finished) == 1, f"want exactly one log record, got {len(finished)}"
|
|
20
|
+
return finished[0]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_event_is_one_named_log_record(logs: InMemoryLogRecordExporter) -> None:
|
|
24
|
+
observability.event(
|
|
25
|
+
"payment.completed",
|
|
26
|
+
domain="payments",
|
|
27
|
+
operation="payment",
|
|
28
|
+
outcome="success",
|
|
29
|
+
entity_type="payment",
|
|
30
|
+
entity_id="pay_123",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
readable = only_record(logs)
|
|
34
|
+
record = readable.log_record
|
|
35
|
+
assert record.event_name == "payment.completed"
|
|
36
|
+
assert record.body == "payment.completed"
|
|
37
|
+
assert record.severity_number == SeverityNumber.INFO
|
|
38
|
+
assert dict(record.attributes or {}) == {
|
|
39
|
+
"event.domain": "payments",
|
|
40
|
+
"event.outcome": "success",
|
|
41
|
+
"business.operation": "payment",
|
|
42
|
+
"business.entity.type": "payment",
|
|
43
|
+
"business.entity.id": "pay_123",
|
|
44
|
+
}
|
|
45
|
+
# Technical context comes from OpenTelemetry's resource, not the caller.
|
|
46
|
+
assert readable.resource.attributes["service.name"] == "shop"
|
|
47
|
+
assert readable.resource.attributes["deployment.environment.name"] == "test"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_only_the_name_is_required(logs: InMemoryLogRecordExporter) -> None:
|
|
51
|
+
observability.event("order.created")
|
|
52
|
+
|
|
53
|
+
record = only_record(logs).log_record
|
|
54
|
+
assert record.event_name == "order.created"
|
|
55
|
+
assert dict(record.attributes or {}) == {}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_event_is_linked_to_the_active_span(logs: InMemoryLogRecordExporter, spans: InMemorySpanExporter) -> None:
|
|
59
|
+
tracer = trace.get_tracer("test")
|
|
60
|
+
with tracer.start_as_current_span("POST /payments") as span:
|
|
61
|
+
observability.event("payment.completed", outcome="success")
|
|
62
|
+
|
|
63
|
+
record = only_record(logs).log_record
|
|
64
|
+
assert record.trace_id == span.get_span_context().trace_id
|
|
65
|
+
assert record.span_id == span.get_span_context().span_id
|
|
66
|
+
# One signal only: no duplicate span event (DOMAIN_EVENTS section 13).
|
|
67
|
+
(finished,) = spans.get_finished_spans()
|
|
68
|
+
assert finished.events == ()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_integer_entity_id_is_recorded_as_text(logs: InMemoryLogRecordExporter) -> None:
|
|
72
|
+
observability.event("loan.submitted", entity_id=42)
|
|
73
|
+
|
|
74
|
+
assert only_record(logs).log_record.attributes == {"business.entity.id": "42"}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_badly_named_event_warns_once_and_is_still_recorded(logs: InMemoryLogRecordExporter) -> None:
|
|
78
|
+
with pytest.warns(OtelStarterWarning, match="<domain>.<action>"):
|
|
79
|
+
observability.event("paymentDone")
|
|
80
|
+
|
|
81
|
+
with warnings.catch_warnings():
|
|
82
|
+
warnings.simplefilter("error") # a second warning would fail here
|
|
83
|
+
observability.event("paymentDone")
|
|
84
|
+
|
|
85
|
+
assert [r.log_record.event_name for r in logs.get_finished_logs()] == ["paymentDone", "paymentDone"]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@pytest.mark.parametrize("name", ["", None, 123])
|
|
89
|
+
def test_unusable_name_is_skipped_with_a_warning(logs: InMemoryLogRecordExporter, name: object) -> None:
|
|
90
|
+
with pytest.warns(OtelStarterWarning, match="non-empty string"):
|
|
91
|
+
observability.event(name) # type: ignore[arg-type]
|
|
92
|
+
|
|
93
|
+
assert logs.get_finished_logs() == ()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_payload_values_are_kept_out(logs: InMemoryLogRecordExporter) -> None:
|
|
97
|
+
with pytest.warns(OtelStarterWarning, match="must be a string or int"):
|
|
98
|
+
observability.event("order.created", entity_id={"card": "4111 1111 1111 1111"}) # type: ignore[arg-type]
|
|
99
|
+
|
|
100
|
+
assert "business.entity.id" not in (only_record(logs).log_record.attributes or {})
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_long_values_are_cut(logs: InMemoryLogRecordExporter) -> None:
|
|
104
|
+
with pytest.warns(OtelStarterWarning, match="looks like a payload"):
|
|
105
|
+
observability.event("order.created", operation="x" * 1000)
|
|
106
|
+
|
|
107
|
+
assert len((only_record(logs).log_record.attributes or {})["business.operation"]) == 256
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_no_catch_all_argument_exists() -> None:
|
|
111
|
+
# Events carry business meaning, not payloads: arbitrary fields are a
|
|
112
|
+
# programming error that type checkers and Python itself reject.
|
|
113
|
+
with pytest.raises(TypeError):
|
|
114
|
+
observability.event("order.created", body={"items": []}) # type: ignore[call-arg]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_internal_failure_never_reaches_the_app(
|
|
118
|
+
logs: InMemoryLogRecordExporter, monkeypatch: pytest.MonkeyPatch
|
|
119
|
+
) -> None:
|
|
120
|
+
def broken_emit(*args: object, **kwargs: object) -> None:
|
|
121
|
+
raise RuntimeError("exporter exploded")
|
|
122
|
+
|
|
123
|
+
monkeypatch.setattr(observability._logger, "emit", broken_emit)
|
|
124
|
+
|
|
125
|
+
with pytest.warns(OtelStarterWarning, match="could not record event"):
|
|
126
|
+
observability.event("payment.completed") # must not raise
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_works_without_opentelemetry_configured() -> None:
|
|
130
|
+
# A fresh interpreter has no SDK configured: event() must be a quiet no-op.
|
|
131
|
+
result = subprocess.run(
|
|
132
|
+
[sys.executable, "-W", "error", "-c", "from otelstarter import observability; observability.event('a.b')"],
|
|
133
|
+
capture_output=True,
|
|
134
|
+
text=True,
|
|
135
|
+
check=False,
|
|
136
|
+
)
|
|
137
|
+
assert result.returncode == 0, result.stderr
|