Skip to content

Commit 4b0c6ed

Browse files
Ruff
1 parent 67e7e8f commit 4b0c6ed

File tree

5 files changed

+78
-71
lines changed

5 files changed

+78
-71
lines changed

instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def hello():
9797
9898
Custom Metrics Attributes using Labeler
9999
***************************************
100-
The Flask instrumentation reads from a Labeler utility that supports adding custom attributes
100+
The Flask instrumentation reads from a Labeler utility that supports adding custom attributes
101101
to the HTTP metrics recorded by the instrumentation.
102102
103103
.. code-block:: python
@@ -113,17 +113,17 @@ def hello():
113113
def user_profile(user_id):
114114
# Get the labeler for the current request
115115
labeler = get_labeler()
116-
116+
117117
# Add custom attributes to Flask instrumentation metrics
118118
labeler.add("user_id", user_id)
119119
labeler.add("user_type", "registered")
120-
120+
121121
# Or, add multiple attributes at once
122122
labeler.add_attributes({
123123
"feature_flag": "new_ui",
124124
"experiment_group": "control"
125125
})
126-
126+
127127
return f"User profile for {user_id}"
128128
129129
@@ -288,6 +288,7 @@ def response_hook(span: Span, status: str, response_headers: List):
288288

289289
import opentelemetry.instrumentation.wsgi as otel_wsgi
290290
from opentelemetry import context, trace
291+
from opentelemetry.instrumentation._labeler import enhance_metric_attributes
291292
from opentelemetry.instrumentation._semconv import (
292293
HTTP_DURATION_HISTOGRAM_BUCKETS_NEW,
293294
_get_schema_url,
@@ -300,7 +301,6 @@ def response_hook(span: Span, status: str, response_headers: List):
300301
from opentelemetry.instrumentation.flask.package import _instruments
301302
from opentelemetry.instrumentation.flask.version import __version__
302303
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
303-
from opentelemetry.instrumentation._labeler import enhance_metric_attributes
304304
from opentelemetry.instrumentation.propagators import (
305305
get_global_response_propagator,
306306
)
@@ -442,9 +442,7 @@ def _start_response(status, response_headers, *args, **kwargs):
442442
)
443443

444444
# Enhance attributes with any custom labeler attributes
445-
duration_attrs_old = enhance_metric_attributes(
446-
duration_attrs_old
447-
)
445+
duration_attrs_old = enhance_metric_attributes(duration_attrs_old)
448446

449447
duration_histogram_old.record(
450448
max(round(duration_s * 1000), 0), duration_attrs_old
@@ -458,9 +456,7 @@ def _start_response(status, response_headers, *args, **kwargs):
458456
duration_attrs_new[HTTP_ROUTE] = str(request_route)
459457

460458
# Enhance attributes with any custom labeler attributes
461-
duration_attrs_new = enhance_metric_attributes(
462-
duration_attrs_new
463-
)
459+
duration_attrs_new = enhance_metric_attributes(duration_attrs_new)
464460

465461
duration_histogram_new.record(
466462
max(duration_s, 0), duration_attrs_new
@@ -490,9 +486,7 @@ def _before_request():
490486
sem_conv_opt_in_mode=sem_conv_opt_in_mode,
491487
)
492488
# Enhance attributes with custom labeler attributes
493-
attributes = enhance_metric_attributes(
494-
attributes
495-
)
489+
attributes = enhance_metric_attributes(attributes)
496490
if flask.request.url_rule:
497491
# For 404 that result from no route found, etc, we
498492
# don't have a url_rule.

opentelemetry-instrumentation/src/opentelemetry/instrumentation/_labeler/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,17 @@
2222

2323
from opentelemetry.instrumentation._labeler._internal import (
2424
Labeler,
25-
get_labeler,
26-
set_labeler,
2725
clear_labeler,
28-
get_labeler_attributes,
2926
enhance_metric_attributes,
27+
get_labeler,
28+
get_labeler_attributes,
29+
set_labeler,
3030
)
3131

3232
__all__ = [
3333
"Labeler",
3434
"get_labeler",
35-
"set_labeler",
35+
"set_labeler",
3636
"clear_labeler",
3737
"get_labeler_attributes",
3838
"enhance_metric_attributes",

opentelemetry-instrumentation/src/opentelemetry/instrumentation/_labeler/_internal/__init__.py

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,21 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import threading
16-
from typing import Dict, Union, Optional, Any
1715
import contextvars
16+
import threading
17+
from typing import Any, Dict, Optional, Union
1818

1919
# Context variable to store the current labeler
20-
_labeler_context: contextvars.ContextVar[Optional["Labeler"]] = contextvars.ContextVar(
21-
"otel_labeler", default=None
20+
_labeler_context: contextvars.ContextVar[Optional["Labeler"]] = (
21+
contextvars.ContextVar("otel_labeler", default=None)
2222
)
2323

2424

2525
class Labeler:
2626
"""
2727
Labeler can be used by instrumented code or distro to add custom attributes
2828
to the metrics recorded by those OpenTelemetry instrumentations reading it.
29-
29+
3030
Labeler accumulates custom attributes for OpenTelemetry metrics for the
3131
current request in context.
3232
@@ -40,28 +40,34 @@ def __init__(self):
4040
def add(self, key: str, value: Union[str, int, float, bool]) -> None:
4141
"""
4242
Add a single attribute to the labeler.
43-
43+
4444
Args:
4545
key: The attribute key
4646
value: The attribute value (must be a primitive type)
4747
"""
4848
if not isinstance(value, (str, int, float, bool)):
49-
raise ValueError(f"Attribute value must be str, int, float, or bool, got {type(value)}")
50-
49+
raise ValueError(
50+
f"Attribute value must be str, int, float, or bool, got {type(value)}"
51+
)
52+
5153
with self._lock:
5254
self._attributes[key] = value
5355

54-
def add_attributes(self, attributes: Dict[str, Union[str, int, float, bool]]) -> None:
56+
def add_attributes(
57+
self, attributes: Dict[str, Union[str, int, float, bool]]
58+
) -> None:
5559
"""
5660
Add multiple attributes to the labeler.
57-
61+
5862
Args:
5963
attributes: Dictionary of attributes to add
6064
"""
6165
for key, value in attributes.items():
6266
if not isinstance(value, (str, int, float, bool)):
63-
raise ValueError(f"Attribute value for '{key}' must be str, int, float, or bool, got {type(value)}")
64-
67+
raise ValueError(
68+
f"Attribute value for '{key}' must be str, int, float, or bool, got {type(value)}"
69+
)
70+
6571
with self._lock:
6672
self._attributes.update(attributes)
6773

@@ -84,10 +90,10 @@ def __len__(self) -> int:
8490
def get_labeler() -> Labeler:
8591
"""
8692
Get the Labeler instance for the current request context.
87-
93+
8894
If no Labeler exists in the current context, a new one is created
8995
and stored in the context.
90-
96+
9197
Returns:
9298
Labeler instance for the current request, or a new empty Labeler
9399
if not in a request context
@@ -102,7 +108,7 @@ def get_labeler() -> Labeler:
102108
def set_labeler(labeler: Labeler) -> None:
103109
"""
104110
Set the Labeler instance for the current request context.
105-
111+
106112
Args:
107113
labeler: The Labeler instance to set
108114
"""
@@ -119,7 +125,7 @@ def clear_labeler() -> None:
119125
def get_labeler_attributes() -> Dict[str, Union[str, int, float, bool]]:
120126
"""
121127
Get attributes from the current labeler, if any.
122-
128+
123129
Returns:
124130
Dictionary of custom attributes, or empty dict if no labeler exists
125131
"""
@@ -130,38 +136,38 @@ def get_labeler_attributes() -> Dict[str, Union[str, int, float, bool]]:
130136

131137

132138
def enhance_metric_attributes(
133-
base_attributes: Dict[str, Any],
139+
base_attributes: Dict[str, Any],
134140
include_custom: bool = True,
135141
max_custom_attrs: int = 20,
136-
max_attr_value_length: int = 100
142+
max_attr_value_length: int = 100,
137143
) -> Dict[str, Any]:
138144
"""
139145
This function combines base_attributes with custom attributes
140146
from the current labeler.
141-
147+
142148
Custom attributes are skipped if they would override base_attributes,
143149
exceed max_custom_attrs number, or are not simple types (str, int, float,
144150
bool). If custom attributes have string values exceeding the
145151
max_attr_value_length, then they are truncated.
146-
152+
147153
Args:
148154
base_attributes: The base attributes for the metric
149155
include_custom: Whether to include custom labeler attributes
150156
max_custom_attrs: Maximum number of custom attributes to include
151157
max_attr_value_length: Maximum length for string attribute values
152-
158+
153159
Returns:
154160
Dictionary combining base and custom attributes
155161
"""
156162
if not include_custom:
157163
return base_attributes.copy()
158-
164+
159165
custom_attributes = get_labeler_attributes()
160166
if not custom_attributes:
161167
return base_attributes.copy()
162-
168+
163169
enhanced_attributes = base_attributes.copy()
164-
170+
165171
added_count = 0
166172
for key, value in custom_attributes.items():
167173
if added_count >= max_custom_attrs:
@@ -175,5 +181,5 @@ def enhance_metric_attributes(
175181
if isinstance(value, (str, int, float, bool)):
176182
enhanced_attributes[key] = value
177183
added_count += 1
178-
184+
179185
return enhanced_attributes

opentelemetry-instrumentation/src/opentelemetry/instrumentation/_labeler/example.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717
"""
1818

1919
from flask import Flask
20-
from opentelemetry.instrumentation.flask import FlaskInstrumentor
20+
2121
from opentelemetry.instrumentation._labeler import get_labeler
22+
from opentelemetry.instrumentation.flask import FlaskInstrumentor
2223

2324
app = Flask(__name__)
2425
FlaskInstrumentor().instrument_app(app)
@@ -29,24 +30,28 @@ def healthcheck():
2930
# Get the labeler for the current request
3031
labeler = get_labeler()
3132

32-
labeler.add_attributes({
33-
"endpoint_type": "healthcheck",
34-
"internal_request": True,
35-
})
33+
labeler.add_attributes(
34+
{
35+
"endpoint_type": "healthcheck",
36+
"internal_request": True,
37+
}
38+
)
3639
return "OK"
3740

3841

3942
@app.route("/user/<user_id>")
4043
def user_profile(user_id):
4144
labeler = get_labeler()
42-
45+
4346
# Can add individual attributes or multiple at once
4447
labeler.add("user_id", user_id)
45-
labeler.add_attributes({
46-
"has_premium": user_id in ["123", "456"],
47-
"experiment_group": "control",
48-
"feature_enabled": True,
49-
"user_segment": "active"
50-
})
51-
48+
labeler.add_attributes(
49+
{
50+
"has_premium": user_id in ["123", "456"],
51+
"experiment_group": "control",
52+
"feature_enabled": True,
53+
"user_segment": "active",
54+
}
55+
)
56+
5257
return f"Got user profile for {user_id}"

0 commit comments

Comments
 (0)