Skip to content

Commit cb45bec

Browse files
authored
Merge branch 'main' into simplify-client-py-6721
2 parents f1f27b7 + 8bca97d commit cb45bec

File tree

26 files changed

+1324
-5
lines changed

26 files changed

+1324
-5
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1212
1313
## Unreleased
1414

15+
- Add experimental composite samplers
16+
([#4714](https://github.com/open-telemetry/opentelemetry-python/pull/4714))
17+
- Filter duplicate logs out of some internal `logger`'s logs on the export logs path that might otherwise endlessly log or cause a recursion depth exceeded issue in cases where logging itself results in an exception.
18+
([#4695](https://github.com/open-telemetry/opentelemetry-python/pull/4695)).
1519
- docs: linked the examples with their github source code location and added Prometheus example
1620
([#4728](https://github.com/open-telemetry/opentelemetry-python/pull/4728))
1721

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import json
16+
import os
17+
import subprocess
18+
import sys
19+
import unittest
20+
21+
22+
class TestMetrics(unittest.TestCase):
23+
def test_metrics(self):
24+
"""Test that metrics example produces expected values"""
25+
# Run the metrics example
26+
test_script = f"{os.path.dirname(os.path.realpath(__file__))}/../metrics_example.py"
27+
28+
result = subprocess.run(
29+
[sys.executable, test_script],
30+
capture_output=True,
31+
text=True,
32+
timeout=10,
33+
check=True,
34+
)
35+
36+
# Script should run successfully
37+
self.assertEqual(result.returncode, 0)
38+
39+
# Parse the JSON output
40+
output_data = json.loads(result.stdout)
41+
42+
# Get the metrics from the JSON structure
43+
metrics = output_data["resource_metrics"][0]["scope_metrics"][0][
44+
"metrics"
45+
]
46+
47+
# Create a lookup dict for easier testing
48+
metrics_by_name = {metric["name"]: metric for metric in metrics}
49+
50+
# Test Counter: should be 1 (called counter.add(1))
51+
counter_value = metrics_by_name["counter"]["data"]["data_points"][0][
52+
"value"
53+
]
54+
self.assertEqual(counter_value, 1, "Counter should have value 1")
55+
56+
# Test UpDownCounter: should be -4 (1 + (-5) = -4)
57+
updown_value = metrics_by_name["updown_counter"]["data"][
58+
"data_points"
59+
][0]["value"]
60+
self.assertEqual(
61+
updown_value, -4, "UpDownCounter should have value -4"
62+
)
63+
64+
# Test Histogram: should have count=1, sum=99.9
65+
histogram_data = metrics_by_name["histogram"]["data"]["data_points"][0]
66+
self.assertEqual(
67+
histogram_data["count"], 1, "Histogram should have count 1"
68+
)
69+
self.assertEqual(
70+
histogram_data["sum"], 99.9, "Histogram should have sum 99.9"
71+
)
72+
73+
# Test Gauge: should be 1 (last value set)
74+
gauge_value = metrics_by_name["gauge"]["data"]["data_points"][0][
75+
"value"
76+
]
77+
self.assertEqual(gauge_value, 1, "Gauge should have value 1")
78+
79+
# Test Observable Counter: should be 1 (from callback)
80+
obs_counter_value = metrics_by_name["observable_counter"]["data"][
81+
"data_points"
82+
][0]["value"]
83+
self.assertEqual(
84+
obs_counter_value, 1, "Observable counter should have value 1"
85+
)
86+
87+
# Test Observable UpDownCounter: should be -10 (from callback)
88+
obs_updown_value = metrics_by_name["observable_updown_counter"][
89+
"data"
90+
]["data_points"][0]["value"]
91+
self.assertEqual(
92+
obs_updown_value,
93+
-10,
94+
"Observable updown counter should have value -10",
95+
)
96+
97+
# Test Observable Gauge: should be 9 (from callback)
98+
obs_gauge_value = metrics_by_name["observable_gauge"]["data"][
99+
"data_points"
100+
][0]["value"]
101+
self.assertEqual(
102+
obs_gauge_value, 9, "Observable gauge should have value 9"
103+
)
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# oltpcollector_example.py
16+
import os
17+
import subprocess
18+
import sys
19+
import unittest
20+
21+
22+
class TestOTLPCollector(unittest.TestCase):
23+
def test_otlpcollector(self):
24+
"""Test that OTLP collector example outputs 'Hello world!'"""
25+
dirpath = os.path.dirname(os.path.realpath(__file__))
26+
test_script = f"{dirpath}/../otlpcollector_example.py"
27+
28+
# Run the script with a short timeout since it will retry forever
29+
with subprocess.Popen(
30+
[sys.executable, test_script],
31+
stdout=subprocess.PIPE,
32+
stderr=subprocess.PIPE,
33+
text=True,
34+
) as process:
35+
# Wait 2 seconds then kill it (enough time to print "Hello world!")
36+
try:
37+
stdout, _ = process.communicate(timeout=2)
38+
except subprocess.TimeoutExpired:
39+
process.kill()
40+
stdout, _ = process.communicate()
41+
42+
# Check that it printed the expected message
43+
self.assertIn("Hello world!", stdout)

exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/exporter.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
KeyValue,
6060
)
6161
from opentelemetry.proto.resource.v1.resource_pb2 import Resource # noqa: F401
62+
from opentelemetry.sdk._shared_internal import DuplicateFilter
6263
from opentelemetry.sdk.environment_variables import (
6364
OTEL_EXPORTER_OTLP_CERTIFICATE,
6465
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE,
@@ -87,6 +88,8 @@
8788
)
8889
_MAX_RETRYS = 6
8990
logger = getLogger(__name__)
91+
# This prevents logs generated when a log fails to be written to generate another log which fails to be written etc. etc.
92+
logger.addFilter(DuplicateFilter())
9093
SDKDataT = TypeVar("SDKDataT")
9194
ResourceDataT = TypeVar("ResourceDataT")
9295
TypingResourceT = TypeVar("TypingResourceT")

exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/_log_exporter/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
LogExporter,
3939
LogExportResult,
4040
)
41+
from opentelemetry.sdk._shared_internal import DuplicateFilter
4142
from opentelemetry.sdk.environment_variables import (
4243
OTEL_EXPORTER_OTLP_CERTIFICATE,
4344
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE,
@@ -57,6 +58,8 @@
5758
from opentelemetry.util.re import parse_env_headers
5859

5960
_logger = logging.getLogger(__name__)
61+
# This prevents logs generated when a log fails to be written to generate another log which fails to be written etc. etc.
62+
_logger.addFilter(DuplicateFilter())
6063

6164

6265
DEFAULT_COMPRESSION = Compression.NoCompression

opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/export/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
set_value,
2828
)
2929
from opentelemetry.sdk._logs import LogData, LogRecord, LogRecordProcessor
30-
from opentelemetry.sdk._shared_internal import BatchProcessor
30+
from opentelemetry.sdk._shared_internal import BatchProcessor, DuplicateFilter
3131
from opentelemetry.sdk.environment_variables import (
3232
OTEL_BLRP_EXPORT_TIMEOUT,
3333
OTEL_BLRP_MAX_EXPORT_BATCH_SIZE,
@@ -43,6 +43,7 @@
4343
"Unable to parse value for %s as integer. Defaulting to %s."
4444
)
4545
_logger = logging.getLogger(__name__)
46+
_logger.addFilter(DuplicateFilter())
4647

4748

4849
class LogExportResult(enum.Enum):

opentelemetry-sdk/src/opentelemetry/sdk/_shared_internal/__init__.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,29 @@
3939
from opentelemetry.util._once import Once
4040

4141

42+
class DuplicateFilter(logging.Filter):
43+
"""Filter that can be applied to internal `logger`'s.
44+
45+
Currently applied to `logger`s on the export logs path that could otherwise cause endless logging of errors or a
46+
recursion depth exceeded issue in cases where logging itself results in an exception."""
47+
48+
def filter(self, record):
49+
current_log = (
50+
record.module,
51+
record.levelno,
52+
record.msg,
53+
# We need to pick a time longer than the OTLP LogExporter timeout
54+
# which defaults to 10 seconds, but not pick something so long that
55+
# it filters out useful logs.
56+
time.time() // 20,
57+
)
58+
if current_log != getattr(self, "last_log", None):
59+
self.last_log = current_log # pylint: disable=attribute-defined-outside-init
60+
return True
61+
# False means python's `logging` module will no longer process this log.
62+
return False
63+
64+
4265
class BatchExportStrategy(enum.Enum):
4366
EXPORT_ALL = 0
4467
EXPORT_WHILE_BATCH_EXCEEDS_THRESHOLD = 1
@@ -89,6 +112,7 @@ def __init__(
89112
daemon=True,
90113
)
91114
self._logger = logging.getLogger(__name__)
115+
self._logger.addFilter(DuplicateFilter())
92116
self._exporting = exporting
93117

94118
self._shutdown = False
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
__all__ = [
16+
"ComposableSampler",
17+
"SamplingIntent",
18+
"composable_always_off",
19+
"composable_always_on",
20+
"composable_parent_threshold",
21+
"composable_traceid_ratio_based",
22+
"composite_sampler",
23+
]
24+
25+
26+
from ._always_off import composable_always_off
27+
from ._always_on import composable_always_on
28+
from ._composable import ComposableSampler, SamplingIntent
29+
from ._parent_threshold import composable_parent_threshold
30+
from ._sampler import composite_sampler
31+
from ._traceid_ratio import composable_traceid_ratio_based
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
from typing import Sequence
18+
19+
from opentelemetry.context import Context
20+
from opentelemetry.trace import Link, SpanKind, TraceState
21+
from opentelemetry.util.types import Attributes
22+
23+
from ._composable import ComposableSampler, SamplingIntent
24+
from ._util import INVALID_THRESHOLD
25+
26+
_intent = SamplingIntent(threshold=INVALID_THRESHOLD, threshold_reliable=False)
27+
28+
29+
class _ComposableAlwaysOffSampler(ComposableSampler):
30+
def sampling_intent(
31+
self,
32+
parent_ctx: Context | None,
33+
name: str,
34+
span_kind: SpanKind | None,
35+
attributes: Attributes,
36+
links: Sequence[Link] | None,
37+
trace_state: TraceState | None = None,
38+
) -> SamplingIntent:
39+
return _intent
40+
41+
def get_description(self) -> str:
42+
return "ComposableAlwaysOff"
43+
44+
45+
_always_off = _ComposableAlwaysOffSampler()
46+
47+
48+
def composable_always_off() -> ComposableSampler:
49+
"""Returns a composable sampler that does not sample any span.
50+
51+
- Always returns a SamplingIntent with no threshold, indicating all spans should be dropped
52+
- Sets threshold_reliable to false
53+
- Does not add any attributes
54+
"""
55+
return _always_off
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
from typing import Sequence
18+
19+
from opentelemetry.context import Context
20+
from opentelemetry.trace import Link, SpanKind, TraceState
21+
from opentelemetry.util.types import Attributes
22+
23+
from ._composable import ComposableSampler, SamplingIntent
24+
from ._util import MIN_THRESHOLD
25+
26+
_intent = SamplingIntent(threshold=MIN_THRESHOLD)
27+
28+
29+
class _ComposableAlwaysOnSampler(ComposableSampler):
30+
def sampling_intent(
31+
self,
32+
parent_ctx: Context | None,
33+
name: str,
34+
span_kind: SpanKind | None,
35+
attributes: Attributes,
36+
links: Sequence[Link] | None,
37+
trace_state: TraceState | None = None,
38+
) -> SamplingIntent:
39+
return _intent
40+
41+
def get_description(self) -> str:
42+
return "ComposableAlwaysOn"
43+
44+
45+
_always_on = _ComposableAlwaysOnSampler()
46+
47+
48+
def composable_always_on() -> ComposableSampler:
49+
"""Returns a composable sampler that samples all spans.
50+
51+
- Always returns a SamplingIntent with threshold set to sample all spans (threshold = 0)
52+
- Sets threshold_reliable to true
53+
- Does not add any attributes
54+
"""
55+
return _always_on

0 commit comments

Comments
 (0)