internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: open-telemetry/opentelemetry-python

Issue:
Should we be handling these exceptions similarly in how we handle shutdown?
Should we be handling these exceptions similarly in how we handle shutdown?

_Originally posted by @lzchen in https://github.com/open-telemetry/opentelemetry-python/pull/2653#discussion_r867005748_


Context:

The `MeterProvider.force_flush()` should probably flush all metric readers and not fail on the first one.


Discussion:
+1 to not failing on the first one. Following [this](https://github.com/open-telemetry/opentelemetry-python/issues/2662#issuecomment-1119112950) we can log the error after.
I am ok, assigning to myself.

Resolving patch:
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_metrics/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_metrics/_internal/__init__.py
--- a/opentelemetry-sdk/src/opentelemetry/sdk/_metrics/_internal/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/_metrics/_internal/__init__.py
@@ -373,12 +373,35 @@ def __init__(
     def force_flush(self, timeout_millis: float = 10_000) -> bool:
         deadline_ns = _time_ns() + timeout_millis * 10**6
 
+        metric_reader_error = {}
+
         for metric_reader in self._sdk_config.metric_readers:
             current_ts = _time_ns()
-            if current_ts >= deadline_ns:
-                raise Exception("Timed out while flushing metric readers")
-            metric_reader.collect(
-                timeout_millis=(deadline_ns - current_ts) / 10**6
+            try:
+                if current_ts >= deadline_ns:
+                    raise Exception("Timed out while flushing metric readers")
+                metric_reader.collect(
+                    timeout_millis=(deadline_ns - current_ts) / 10**6
+                )
+
+            # pylint: disable=broad-except
+            except Exception as error:
+
+                metric_reader_error[metric_reader] = error
+
+        if metric_reader_error:
+
+            metric_reader_error_string = "\n".join(
+                [
+                    f"{metric_reader.__class__.__name__}: {repr(error)}"
+                    for metric_reader, error in metric_reader_error.items()
+                ]
+            )
+
+            raise Exception(
+                "MeterProvider.force_flush failed because the following "
+                "metric readers failed during collect:\n"
+                f"{metric_reader_error_string}"
             )
         return True
 


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Document that passing attributes at the time of span creation is preferred.
Following https://github.com/open-telemetry/opentelemetry-specification/pull/2383


Discussion:

Resolving patch:
diff --git a/opentelemetry-api/src/opentelemetry/trace/span.py b/opentelemetry-api/src/opentelemetry/trace/span.py
--- a/opentelemetry-api/src/opentelemetry/trace/span.py
+++ b/opentelemetry-api/src/opentelemetry/trace/span.py
@@ -86,7 +86,10 @@ def set_attributes(
 
         Sets Attributes with the key and value passed as arguments dict.
 
-        Note: The behavior of `None` value attributes is undefined, and hence strongly discouraged.
+        Note: The behavior of `None` value attributes is undefined, and hence
+        strongly discouraged. It is also preferred to set attributes at span
+        creation, instead of calling this method later since samplers can only
+        consider information already present during span creation.
         """
 
     @abc.abstractmethod
@@ -95,7 +98,10 @@ def set_attribute(self, key: str, value: types.AttributeValue) -> None:
 
         Sets a single Attribute with the key and value passed as arguments.
 
-        Note: The behavior of `None` value attributes is undefined, and hence strongly discouraged.
+        Note: The behavior of `None` value attributes is undefined, and hence
+        strongly discouraged. It is also preferred to set attributes at span
+        creation, instead of calling this method later since samplers can only
+        consider information already present during span creation.
         """
 
     @abc.abstractmethod


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
LogEmitterProvider.force_flush hangs and ultimately timeouts randomly
**Describe your environment** 
Python 3.6.8
Opentelemetry Python 1.7.1
Opentelemetry Collector 0.38.0

**Steps to reproduce**
Note that this is a random behavior.
Regularly call LogEmitterProvider.force_flush while emitting logs.
We're using the BatchLogProcessor with schedule_delay_millis=200

**What is the expected behavior?**
No hanging

**What is the actual behavior?**
Hanging randomly

**Additional context**




Discussion:

Resolving patch:
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/export/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/export/__init__.py
--- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/export/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/export/__init__.py
@@ -178,7 +178,7 @@ def worker(self):
                 flush_request = self._get_and_unset_flush_request()
                 if (
                     len(self._queue) < self._max_export_batch_size
-                    and self._flush_request is None
+                    and flush_request is None
                 ):
                     self._condition.wait(timeout)
 


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Add an example to show how to drop measurements from an instrument
Part of #2733 


Discussion:

Resolving patch:
diff --git a/docs/examples/views/drop_metrics_from_instrument.py b/docs/examples/views/drop_metrics_from_instrument.py
new file mode 100644
--- /dev/null
+++ b/docs/examples/views/drop_metrics_from_instrument.py
@@ -0,0 +1,53 @@
+# Copyright The OpenTelemetry Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import random
+import time
+
+from opentelemetry.metrics import get_meter_provider, set_meter_provider
+from opentelemetry.sdk.metrics import Counter, MeterProvider
+from opentelemetry.sdk.metrics.export import (
+    ConsoleMetricExporter,
+    PeriodicExportingMetricReader,
+)
+from opentelemetry.sdk.metrics.view import DropAggregation, View
+
+# Create a view matching the counter instrument `my.counter`
+# and configure the view to drop the aggregation.
+drop_aggregation_view = View(
+    instrument_type=Counter,
+    instrument_name="my.counter",
+    aggregation=DropAggregation(),
+)
+
+exporter = ConsoleMetricExporter()
+
+reader = PeriodicExportingMetricReader(exporter, export_interval_millis=1_000)
+provider = MeterProvider(
+    metric_readers=[
+        reader,
+    ],
+    views=[
+        drop_aggregation_view,
+    ],
+)
+set_meter_provider(provider)
+
+meter = get_meter_provider().get_meter("view-drop-aggregation", "0.1.2")
+
+my_counter = meter.create_counter("my.counter")
+
+while 1:
+    my_counter.add(random.randint(1, 10))
+    time.sleep(random.random())


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
SDK tests show error message
When running SDK tests this message shows up:

```
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "/home/ocelotl/github/ocelotl/opentelemetry-python/.tox/py39-opentelemetry-sdk/lib/python3.9/site-packages/opentelemetry/sdk/metrics/_internal/__init__.py", line 422, in shutdown
    did_shutdown = self._shutdown_once.do_once(_shutdown)
AttributeError: 'MeterProvider' object has no attribute '_shutdown_once'
```
While it is harmless, it is annoying, stop it from showing up.


Discussion:

Resolving patch:
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py
--- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py
@@ -357,6 +357,8 @@ def __init__(
             self._atexit_handler = register(self.shutdown)
 
         self._meters = {}
+        self._shutdown_once = Once()
+        self._shutdown = False
 
         for metric_reader in self._sdk_config.metric_readers:
 
@@ -373,9 +375,6 @@ def __init__(
                 self._measurement_consumer.collect
             )
 
-        self._shutdown_once = Once()
-        self._shutdown = False
-
     def force_flush(self, timeout_millis: float = 10_000) -> bool:
         deadline_ns = _time_ns() + timeout_millis * 10**6
 


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Update the default explicit histogram buckets
Buckets should be updated with new values given here https://github.com/open-telemetry/opentelemetry-specification/pull/2770


Discussion:

Resolving patch:
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py
--- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py
@@ -227,7 +227,12 @@ def __init__(
             100.0,
             250.0,
             500.0,
+            750.0,
             1000.0,
+            2500.0,
+            5000.0,
+            7500.0,
+            10000.0,
         ),
         record_min_max: bool = True,
     ):
@@ -454,7 +459,12 @@ def __init__(
             100.0,
             250.0,
             500.0,
+            750.0,
             1000.0,
+            2500.0,
+            5000.0,
+            7500.0,
+            10000.0,
         ),
         record_min_max: bool = True,
     ) -> None:


Test patch:
diff --git a/opentelemetry-sdk/tests/metrics/test_aggregation.py b/opentelemetry-sdk/tests/metrics/test_aggregation.py
--- a/opentelemetry-sdk/tests/metrics/test_aggregation.py
+++ b/opentelemetry-sdk/tests/metrics/test_aggregation.py
@@ -378,6 +378,28 @@ def test_collect(self):
             second_histogram.time_unix_nano, first_histogram.time_unix_nano
         )
 
+    def test_boundaries(self):
+        self.assertEqual(
+            _ExplicitBucketHistogramAggregation(Mock(), 0)._boundaries,
+            (
+                0.0,
+                5.0,
+                10.0,
+                25.0,
+                50.0,
+                75.0,
+                100.0,
+                250.0,
+                500.0,
+                750.0,
+                1000.0,
+                2500.0,
+                5000.0,
+                7500.0,
+                10000.0,
+            ),
+        )
+
 
 class TestAggregationFactory(TestCase):
     def test_sum_factory(self):
Repository: open-telemetry/opentelemetry-python

Issue:
Fix dead link
There is a dead link in the CHANGELOG, [here](https://github.com/open-telemetry/opentelemetry-python/blob/main/CHANGELOG.md?plain=1#L13).


Discussion:

Resolving patch:
diff --git a/scripts/eachdist.py b/scripts/eachdist.py
--- a/scripts/eachdist.py
+++ b/scripts/eachdist.py
@@ -675,7 +675,7 @@ def release_args(args):
         update_dependencies(targets, version, packages)
         update_version_files(targets, version, packages)
 
-    update_changelogs("-".join(updated_versions))
+    update_changelogs(updated_versions[0])
 
 
 def test_args(args):


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Add metrics export to gunicorn example
`gunicorn` section in OpenTelemetry documentation should be improved with an additional example of exporting metrics. This is useful for future users to avoid the surprise of weird metric behavior as in a fork-process model each worker generates its own metrics. If metric attributes do not account for worker identity, then end results might be surprising.



Discussion:

Resolving patch:
diff --git a/docs/examples/fork-process-model/flask-gunicorn/gunicorn.config.py b/docs/examples/fork-process-model/flask-gunicorn/gunicorn.conf.py
similarity index 57%
rename from docs/examples/fork-process-model/flask-gunicorn/gunicorn.config.py
rename to docs/examples/fork-process-model/flask-gunicorn/gunicorn.conf.py
--- a/docs/examples/fork-process-model/flask-gunicorn/gunicorn.config.py
+++ b/docs/examples/fork-process-model/flask-gunicorn/gunicorn.conf.py
@@ -12,10 +12,15 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-from opentelemetry import trace
+from opentelemetry import metrics, trace
+from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import (
+    OTLPMetricExporter,
+)
 from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
     OTLPSpanExporter,
 )
+from opentelemetry.sdk.metrics import MeterProvider
+from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
 from opentelemetry.sdk.resources import Resource
 from opentelemetry.sdk.trace import TracerProvider
 from opentelemetry.sdk.trace.export import BatchSpanProcessor
@@ -41,7 +46,19 @@
 def post_fork(server, worker):
     server.log.info("Worker spawned (pid: %s)", worker.pid)
 
-    resource = Resource.create(attributes={"service.name": "api-service"})
+    resource = Resource.create(
+        attributes={
+            "service.name": "api-service",
+            # If workers are not distinguished within attributes, traces and
+            # metrics exported from each worker will be indistinguishable. While
+            # not necessarily an issue for traces, it is confusing for almost
+            # all metric types. A built-in way to identify a worker is by PID
+            # but this may lead to high label cardinality. An alternative
+            # workaround and additional discussion are available here:
+            # https://github.com/benoitc/gunicorn/issues/1352
+            "worker": worker.pid,
+        }
+    )
 
     trace.set_tracer_provider(TracerProvider(resource=resource))
     # This uses insecure connection for the purpose of example. Please see the
@@ -50,3 +67,13 @@ def post_fork(server, worker):
         OTLPSpanExporter(endpoint="http://localhost:4317", insecure=True)
     )
     trace.get_tracer_provider().add_span_processor(span_processor)
+
+    reader = PeriodicExportingMetricReader(
+        OTLPMetricExporter(endpoint="http://localhost:4317")
+    )
+    metrics.set_meter_provider(
+        MeterProvider(
+            resource=resource,
+            metric_readers=[reader],
+        )
+    )


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Add metrics example of Prometheus to Grafana



Discussion:
Should this be in the metrics stable project?
> Should this be in the metrics stable project?

Just for the record, we decided it was not necessary for this to be in the metrics stable project.
@srikanthccv I would like to work on this issue, should I go ahead

I have assigned this to you. Let me know if you have any questions.
@srikanthccv, kindly  guide me on how Prometheus is set up on this application, and how you run it
You can follow this getting started guide to run Prometheus on your machine https://prometheus.io/docs/prometheus/latest/getting_started/. And here we have the exporter that can be scraped by Prometheus https://github.com/open-telemetry/opentelemetry-python/tree/main/exporter/opentelemetry-exporter-prometheus. You need to add a complete example of how to emit some metrics and make see they show up in UI.

Resolving patch:
diff --git a/docs/examples/metrics/prometheus-grafana/prometheus-monitor.py b/docs/examples/metrics/prometheus-grafana/prometheus-monitor.py
new file mode 100644
--- /dev/null
+++ b/docs/examples/metrics/prometheus-grafana/prometheus-monitor.py
@@ -0,0 +1,23 @@
+import random
+import time
+
+from prometheus_client import start_http_server
+
+from opentelemetry.exporter.prometheus import PrometheusMetricReader
+from opentelemetry.metrics import get_meter_provider, set_meter_provider
+from opentelemetry.sdk.metrics import MeterProvider
+
+# Start Prometheus client
+start_http_server(port=8000, addr="localhost")
+# Exporter to export metrics to Prometheus
+prefix = "MyAppPrefix"
+reader = PrometheusMetricReader(prefix)
+# Meter is responsible for creating and recording metrics
+set_meter_provider(MeterProvider(metric_readers=[reader]))
+meter = get_meter_provider().get_meter("view-name-change", "0.1.2")
+
+my_counter = meter.create_counter("my.counter")
+
+while 1:
+    my_counter.add(random.randint(1, 10))
+    time.sleep(random.random())


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
'set_logger_provider' no longer importable from 'opentelemetry.sdk._logs'
A week ago I was able to run the example for logging in https://github.com/open-telemetry/opentelemetry-python/tree/main/docs/examples/logs.

**Steps to reproduce**
I install either version via:
```bash
pip install opentelemetry-exporter-otlp==1.15.0
```
or
```bash
pip install opentelemetry-exporter-otlp==1.14.0
```
Then run the following code:
```python
from opentelemetry.sdk._logs import set_logger_provider
```

**What is the expected behavior?**
Should import  without any issues.

**What is the actual behavior?**
```python
ImportError: cannot import name 'set_logger_provider' from 'opentelemetry.sdk._logs' (/usr/local/lib/python3.10/dist-packages/opentelemetry/sdk/_logs/__init__.py)
```


**Additional context**
I found that when I installed `opentelemetry-exporter-otlp==1.14.0`, `opentelemetry-sdk==1.15.0` was installed as well. When I installed `opentelemetry-sdk==1.14.0`, everything works fine again.



Discussion:
same ttrying to run the example and it failed
Yes, the example shown here:

https://github.com/open-telemetry/opentelemetry-python/blob/main/docs/examples/logs/example.py#L10

no longer works with the `1.15.0` release. Is there a change in the package and how this should work going forward?
I've encountered the same problem and searched for the method in the source code and found it at a new location:
`from opentelemetry._logs import set_logger_provider`
Would someone like to send a PR to update the example?
> Would someone like to send a PR to update the example?

Yes, I'd be happy to send a PR. 

Resolving patch:
diff --git a/docs/examples/logs/example.py b/docs/examples/logs/example.py
--- a/docs/examples/logs/example.py
+++ b/docs/examples/logs/example.py
@@ -1,14 +1,11 @@
 import logging
 
 from opentelemetry import trace
+from opentelemetry._logs import set_logger_provider
 from opentelemetry.exporter.otlp.proto.grpc._log_exporter import (
     OTLPLogExporter,
 )
-from opentelemetry.sdk._logs import (
-    LoggerProvider,
-    LoggingHandler,
-    set_logger_provider,
-)
+from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
 from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
 from opentelemetry.sdk.resources import Resource
 from opentelemetry.sdk.trace import TracerProvider


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
A minor typo in doc: https://opentelemetry-python.readthedocs.io/en/latest/api/trace.html
Hello but sorry to interrupt that I need to correct the typo I found in https://opentelemetry-python.readthedocs.io/en/latest/api/trace.html

The typo occurs at the code snippet below:

_This can also be used as a decorator:_
```
@tracer.start_as_current_span("name"):
def function():
    ...

function()
```

where the first colon after the @ statement is an extra.


_**Please correct me if I myself made a mistake posting this. Thanks.**_


Discussion:
You are correct. Please send a pull request.

Resolving patch:
diff --git a/opentelemetry-api/src/opentelemetry/trace/__init__.py b/opentelemetry-api/src/opentelemetry/trace/__init__.py
--- a/opentelemetry-api/src/opentelemetry/trace/__init__.py
+++ b/opentelemetry-api/src/opentelemetry/trace/__init__.py
@@ -373,7 +373,7 @@ def start_as_current_span(
 
         This can also be used as a decorator::
 
-            @tracer.start_as_current_span("name"):
+            @tracer.start_as_current_span("name")
             def function():
                 ...
 


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Update lint and other environments to 3.10
Right now we use 3.9 to run lint and other test environments, update to 3.10.


Discussion:

Resolving patch:
diff --git a/scripts/public_symbols_checker.py b/scripts/public_symbols_checker.py
--- a/scripts/public_symbols_checker.py
+++ b/scripts/public_symbols_checker.py
@@ -76,9 +76,11 @@ def get_symbols(change_type, diff_lines_getter, prefix):
 def a_diff_lines_getter(diff_lines):
     return diff_lines.b_blob.data_stream.read().decode("utf-8").split("\n")
 
+
 def d_diff_lines_getter(diff_lines):
     return diff_lines.a_blob.data_stream.read().decode("utf-8").split("\n")
 
+
 def m_diff_lines_getter(diff_lines):
     return unified_diff(
         diff_lines.a_blob.data_stream.read().decode("utf-8").split("\n"),
@@ -91,6 +93,7 @@ def m_diff_lines_getter(diff_lines):
 get_symbols("M", m_diff_lines_getter, r"\+")
 get_symbols("M", m_diff_lines_getter, r"\-")
 
+
 def remove_common_symbols():
     # For each file, we remove the symbols that are added and removed in the
     # same commit.
@@ -115,6 +118,7 @@ def remove_common_symbols():
         if not removed_symbols[file_path]:
             del removed_symbols[file_path]
 
+
 if added_symbols or removed_symbols:
 
     # If a symbol is added and removed in the same commit, we consider it
@@ -122,10 +126,10 @@ def remove_common_symbols():
     remove_common_symbols()
     print("The code in this branch adds the following public symbols:")
     print()
-    for file_path, symbols in added_symbols.items():
-        print(f"- {file_path}")
-        for symbol in symbols:
-            print(f"\t{symbol}")
+    for file_path_, symbols_ in added_symbols.items():
+        print(f"- {file_path_}")
+        for symbol_ in symbols_:
+            print(f"\t{symbol_}")
         print()
 
     print(
@@ -137,10 +141,10 @@ def remove_common_symbols():
     print()
     print("The code in this branch removes the following public symbols:")
     print()
-    for file_path, symbols in removed_symbols.items():
-        print(f"- {file_path}")
-        for symbol in symbols:
-            print(f"\t{symbol}")
+    for file_path_, symbols_ in removed_symbols.items():
+        print(f"- {file_path_}")
+        for symbol_ in symbols_:
+            print(f"\t{symbol_}")
         print()
 
     print(


Test patch:
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -101,7 +101,7 @@ jobs:
     - name: Set up Python
       uses: actions/setup-python@v2
       with:
-        python-version: 3.9
+        python-version: '3.10'
         architecture: 'x64'
     - name: Install tox
       run: pip install tox==3.27.1