From 85aa8732fa212646bb7f35084ba99c26f7e24b45 Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Wed, 29 Apr 2026 18:03:43 +0200 Subject: [PATCH 01/12] Add opentelemetry-instrumentation-exceptions package Signed-off-by: Israel Blancas --- .github/component_owners.yml | 3 + .github/workflows/core_contrib_test.yml | 30 +++ .github/workflows/lint.yml | 19 ++ .github/workflows/test.yml | 114 +++++++++ CHANGELOG.md | 2 + .../instrumentation/exceptions/exceptions.rst | 7 + instrumentation/README.md | 1 + .../LICENSE | 13 + .../README.rst | 35 +++ .../pyproject.toml | 53 ++++ .../instrumentation/exceptions/__init__.py | 212 ++++++++++++++++ .../instrumentation/exceptions/package.py | 17 ++ .../instrumentation/exceptions/version.py | 15 ++ .../test-requirements.txt | 13 + .../tests/test_exceptions.py | 239 ++++++++++++++++++ .../pyproject.toml | 1 + .../instrumentation/bootstrap_gen.py | 1 + tox.ini | 11 + 18 files changed, 786 insertions(+) create mode 100644 docs/instrumentation/exceptions/exceptions.rst create mode 100644 instrumentation/opentelemetry-instrumentation-exceptions/LICENSE create mode 100644 instrumentation/opentelemetry-instrumentation-exceptions/README.rst create mode 100644 instrumentation/opentelemetry-instrumentation-exceptions/pyproject.toml create mode 100644 instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py create mode 100644 instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/package.py create mode 100644 instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/version.py create mode 100644 instrumentation/opentelemetry-instrumentation-exceptions/test-requirements.txt create mode 100644 instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py diff --git a/.github/component_owners.yml b/.github/component_owners.yml index 25a0a06e4b..2a192de85b 100644 --- a/.github/component_owners.yml +++ b/.github/component_owners.yml @@ -12,6 +12,9 @@ components: instrumentation/opentelemetry-instrumentation-asyncio: - bourbonkk + instrumentation/opentelemetry-instrumentation-exceptions: + - iblancasa + instrumentation/opentelemetry-instrumentation-botocore: - lukeina2z - yiyuan-he diff --git a/.github/workflows/core_contrib_test.yml b/.github/workflows/core_contrib_test.yml index d9f90d57d8..43d0625931 100644 --- a/.github/workflows/core_contrib_test.yml +++ b/.github/workflows/core_contrib_test.yml @@ -1827,6 +1827,36 @@ jobs: - name: Run tests run: tox -e py310-test-instrumentation-logging -- -ra + py310-test-instrumentation-exceptions: + name: instrumentation-exceptions + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout contrib repo @ SHA - ${{ env.CONTRIB_REPO_SHA }} + uses: actions/checkout@v4 + with: + repository: open-telemetry/opentelemetry-python-contrib + ref: ${{ env.CONTRIB_REPO_SHA }} + + - name: Checkout core repo @ SHA - ${{ env.CORE_REPO_SHA }} + uses: actions/checkout@v4 + with: + repository: open-telemetry/opentelemetry-python + ref: ${{ env.CORE_REPO_SHA }} + path: opentelemetry-python + + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: "3.10" + architecture: "x64" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py310-test-instrumentation-exceptions -- -ra + py310-test-exporter-richconsole: name: exporter-richconsole runs-on: ubuntu-latest diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 6bf3c631cd..8ef635106c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -613,6 +613,25 @@ jobs: - name: Run tests run: tox -e lint-instrumentation-logging + lint-instrumentation-exceptions: + name: instrumentation-exceptions + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.14 + uses: actions/setup-python@v5 + with: + python-version: "3.14" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e lint-instrumentation-exceptions + lint-exporter-richconsole: name: exporter-richconsole runs-on: ubuntu-latest diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9c694007ea..19520e3a99 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6142,6 +6142,120 @@ jobs: - name: Run tests run: tox -e pypy3-test-instrumentation-logging -- -ra + py310-test-instrumentation-exceptions_ubuntu-latest: + name: instrumentation-exceptions 3.10 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: "3.10" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py310-test-instrumentation-exceptions -- -ra + + py311-test-instrumentation-exceptions_ubuntu-latest: + name: instrumentation-exceptions 3.11 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.11 + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py311-test-instrumentation-exceptions -- -ra + + py312-test-instrumentation-exceptions_ubuntu-latest: + name: instrumentation-exceptions 3.12 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py312-test-instrumentation-exceptions -- -ra + + py313-test-instrumentation-exceptions_ubuntu-latest: + name: instrumentation-exceptions 3.13 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.13 + uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py313-test-instrumentation-exceptions -- -ra + + py314-test-instrumentation-exceptions_ubuntu-latest: + name: instrumentation-exceptions 3.14 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python 3.14 + uses: actions/setup-python@v5 + with: + python-version: "3.14" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e py314-test-instrumentation-exceptions -- -ra + + pypy3-test-instrumentation-exceptions_ubuntu-latest: + name: instrumentation-exceptions pypy-3.10 Ubuntu + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repo @ SHA - ${{ github.sha }} + uses: actions/checkout@v4 + + - name: Set up Python pypy-3.10 + uses: actions/setup-python@v5 + with: + python-version: "pypy-3.10" + + - name: Install tox + run: pip install tox-uv + + - name: Run tests + run: tox -e pypy3-test-instrumentation-exceptions -- -ra + py310-test-exporter-richconsole_ubuntu-latest: name: exporter-richconsole 3.10 Ubuntu runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 93f0cab4fc..0d3d1ed7e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#4335](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4335)) - Expand `AGENTS.md` with instrumentation/GenAI guidance and add PR review instructions. ([#4457](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4457)) +- `opentelemetry-instrumentation-exceptions`: Add instrumentation to emit OpenTelemetry logs for uncaught exceptions, uncaught thread exceptions, and unhandled asyncio task exceptions. + ([#4209](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/4209)) ### Fixed diff --git a/docs/instrumentation/exceptions/exceptions.rst b/docs/instrumentation/exceptions/exceptions.rst new file mode 100644 index 0000000000..4ae46f16e6 --- /dev/null +++ b/docs/instrumentation/exceptions/exceptions.rst @@ -0,0 +1,7 @@ +OpenTelemetry Exceptions Instrumentation +======================================== + +.. automodule:: opentelemetry.instrumentation.exceptions + :members: + :undoc-members: + :show-inheritance: diff --git a/instrumentation/README.md b/instrumentation/README.md index 8d9a247945..a430f60364 100644 --- a/instrumentation/README.md +++ b/instrumentation/README.md @@ -20,6 +20,7 @@ | [opentelemetry-instrumentation-dbapi](./opentelemetry-instrumentation-dbapi) | dbapi | No | development | [opentelemetry-instrumentation-django](./opentelemetry-instrumentation-django) | django >= 2.0 | Yes | development | [opentelemetry-instrumentation-elasticsearch](./opentelemetry-instrumentation-elasticsearch) | elasticsearch >= 6.0 | No | development +| [opentelemetry-instrumentation-exceptions](./opentelemetry-instrumentation-exceptions) | exceptions | No | development | [opentelemetry-instrumentation-falcon](./opentelemetry-instrumentation-falcon) | falcon >= 1.4.1, < 5.0.0 | Yes | migration | [opentelemetry-instrumentation-fastapi](./opentelemetry-instrumentation-fastapi) | fastapi ~= 0.92 | Yes | migration | [opentelemetry-instrumentation-flask](./opentelemetry-instrumentation-flask) | flask >= 1.0 | Yes | migration diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/LICENSE b/instrumentation/opentelemetry-instrumentation-exceptions/LICENSE new file mode 100644 index 0000000000..b0a6f42841 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-exceptions/LICENSE @@ -0,0 +1,13 @@ +# 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. diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/README.rst b/instrumentation/opentelemetry-instrumentation-exceptions/README.rst new file mode 100644 index 0000000000..0fb4ada53c --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-exceptions/README.rst @@ -0,0 +1,35 @@ +OpenTelemetry unhandled exceptions instrumentation +================================================== + +|pypi| + +.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-exceptions.svg + :target: https://pypi.org/project/opentelemetry-instrumentation-exceptions/ + +Installation +------------ + +:: + + pip install opentelemetry-instrumentation-exceptions + +Usage +----- + +.. code-block:: python + + from opentelemetry.instrumentation.exceptions import ( + UnhandledExceptionInstrumentor, + ) + + UnhandledExceptionInstrumentor().instrument() + +This instrumentation captures uncaught process exceptions, uncaught thread +exceptions, and unhandled asyncio task exceptions and emits them as OpenTelemetry +logs. + +References +---------- + +* `OpenTelemetry unhandled exceptions instrumentation `_ +* `OpenTelemetry Project `_ diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/pyproject.toml b/instrumentation/opentelemetry-instrumentation-exceptions/pyproject.toml new file mode 100644 index 0000000000..3fe7d47c14 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-exceptions/pyproject.toml @@ -0,0 +1,53 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "opentelemetry-instrumentation-exceptions" +dynamic = ["version"] +description = "OpenTelemetry unhandled exceptions instrumentation" +readme = "README.rst" +license = "Apache-2.0" +requires-python = ">=3.10" +authors = [ + { name = "OpenTelemetry Authors", email = "cncf-opentelemetry-contributors@lists.cncf.io" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] +dependencies = [ + "opentelemetry-api >= 1.42.0.dev, < 2.0.0", + "opentelemetry-instrumentation == 0.63b0.dev", + "opentelemetry-semantic-conventions == 0.63b0.dev", +] + +[project.optional-dependencies] +instruments = [] + +[project.entry-points.opentelemetry_instrumentor] +exceptions = "opentelemetry.instrumentation.exceptions:UnhandledExceptionInstrumentor" + +[project.urls] +Homepage = "https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-exceptions" +Repository = "https://github.com/open-telemetry/opentelemetry-python-contrib" + +[tool.hatch.version] +path = "src/opentelemetry/instrumentation/exceptions/version.py" + +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", +] + +[tool.hatch.build.targets.wheel] +packages = ["src/opentelemetry"] diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py new file mode 100644 index 0000000000..c5495f07d5 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py @@ -0,0 +1,212 @@ +# 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. +""" +Instrument uncaught exceptions to emit OpenTelemetry logs. + +Usage +----- + +.. code-block:: python + + from opentelemetry.instrumentation.exceptions import ( + UnhandledExceptionInstrumentor, + ) + + UnhandledExceptionInstrumentor().instrument() + +This instrumentation captures uncaught process exceptions, uncaught thread +exceptions, and unhandled asyncio task exceptions and emits them as +OpenTelemetry logs. +""" + +from __future__ import annotations + +import asyncio +import sys +import threading +from collections.abc import Collection +from types import TracebackType +from typing import Any, Callable + +from opentelemetry._logs import SeverityNumber, get_logger +from opentelemetry.instrumentation.exceptions.package import _instruments +from opentelemetry.instrumentation.exceptions.version import __version__ +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.semconv.schemas import Schemas + + +class _ExceptionLogger: + def __init__(self, logger_provider: Any = None): + self._logger = get_logger( + __name__, + __version__, + logger_provider, + schema_url=Schemas.V1_37_0.value, + ) + + def emit( + self, + exc: Exception, + *, + severity_text: str, + severity_number: SeverityNumber, + ) -> None: + self._logger.emit( + body=str(exc), + severity_text=severity_text, + severity_number=severity_number, + exception=exc, + ) + + +class UnhandledExceptionInstrumentor(BaseInstrumentor): + """Emit logs for uncaught exceptions and unhandled asyncio exceptions.""" + + def __init__(self, logger_provider: Any = None): + super().__init__() + self._logger_provider = logger_provider + self._exception_logger: _ExceptionLogger | None = None + self._original_sys_excepthook: Callable[..., Any] | None = None + self._original_threading_excepthook: Callable[..., Any] | None = None + self._original_asyncio_call_exception_handler: ( + Callable[..., Any] | None + ) = None + self._sys_excepthook: Callable[..., Any] | None = None + self._threading_excepthook: Callable[..., Any] | None = None + self._asyncio_call_exception_handler: Callable[..., Any] | None = None + + def instrumentation_dependencies(self) -> Collection[str]: + return _instruments + + def _instrument(self, **kwargs: Any): + logger_provider = kwargs.get("logger_provider", self._logger_provider) + self._exception_logger = _ExceptionLogger(logger_provider) + self._install_sys_hook() + self._install_threading_hook() + self._install_asyncio_hook() + + def _uninstrument(self, **kwargs: Any): + self._restore_sys_hook() + self._restore_threading_hook() + self._restore_asyncio_hook() + self._exception_logger = None + + def _install_sys_hook(self) -> None: + if self._original_sys_excepthook is not None: + return + + self._original_sys_excepthook = sys.excepthook + + def _handle_sys_exc( + exc_type: type[BaseException], + exc: BaseException, + tb: TracebackType | None, + ) -> None: + if isinstance(exc, Exception) and self._exception_logger is not None: + try: + self._exception_logger.emit( + exc, + severity_text="FATAL", + severity_number=SeverityNumber.FATAL, + ) + except Exception: # pragma: no cover # pylint: disable=broad-exception-caught + pass + self._original_sys_excepthook(exc_type, exc, tb) + + self._sys_excepthook = _handle_sys_exc + sys.excepthook = _handle_sys_exc + + def _restore_sys_hook(self) -> None: + if ( + self._original_sys_excepthook is not None + and sys.excepthook is self._sys_excepthook + ): + sys.excepthook = self._original_sys_excepthook + self._original_sys_excepthook = None + self._sys_excepthook = None + + def _install_threading_hook(self) -> None: + if self._original_threading_excepthook is not None: + return + + self._original_threading_excepthook = threading.excepthook + + def _handle_threading_exc(args: threading.ExceptHookArgs) -> None: + if ( + isinstance(args.exc_value, Exception) + and self._exception_logger is not None + ): + try: + self._exception_logger.emit( + args.exc_value, + severity_text="ERROR", + severity_number=SeverityNumber.ERROR, + ) + except Exception: # pragma: no cover # pylint: disable=broad-exception-caught + pass + self._original_threading_excepthook(args) + + self._threading_excepthook = _handle_threading_exc + threading.excepthook = _handle_threading_exc + + def _restore_threading_hook(self) -> None: + if ( + self._original_threading_excepthook is not None + and threading.excepthook is self._threading_excepthook + ): + threading.excepthook = self._original_threading_excepthook + self._original_threading_excepthook = None + self._threading_excepthook = None + + def _install_asyncio_hook(self) -> None: + if self._original_asyncio_call_exception_handler is not None: + return + + self._original_asyncio_call_exception_handler = ( + asyncio.BaseEventLoop.call_exception_handler + ) + + def _call_exception_handler( + loop: asyncio.AbstractEventLoop, + context: dict[str, Any], + ) -> None: + exc = context.get("exception") + if isinstance(exc, Exception) and self._exception_logger is not None: + try: + self._exception_logger.emit( + exc, + severity_text="ERROR", + severity_number=SeverityNumber.ERROR, + ) + except Exception: # pragma: no cover # pylint: disable=broad-exception-caught + pass + self._original_asyncio_call_exception_handler(loop, context) + + self._asyncio_call_exception_handler = _call_exception_handler + asyncio.BaseEventLoop.call_exception_handler = _call_exception_handler + + def _restore_asyncio_hook(self) -> None: + if ( + self._original_asyncio_call_exception_handler is not None + and asyncio.BaseEventLoop.call_exception_handler + is self._asyncio_call_exception_handler + ): + asyncio.BaseEventLoop.call_exception_handler = ( + self._original_asyncio_call_exception_handler + ) + self._original_asyncio_call_exception_handler = None + self._asyncio_call_exception_handler = None + + +__all__ = ["UnhandledExceptionInstrumentor"] diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/package.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/package.py new file mode 100644 index 0000000000..1bf177779b --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/package.py @@ -0,0 +1,17 @@ +# 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. + +_instruments = () + +_supports_metrics = False diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/version.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/version.py new file mode 100644 index 0000000000..a07bc2663e --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/version.py @@ -0,0 +1,15 @@ +# 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. + +__version__ = "0.63b0.dev" diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/test-requirements.txt b/instrumentation/opentelemetry-instrumentation-exceptions/test-requirements.txt new file mode 100644 index 0000000000..ba0e2e83ff --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-exceptions/test-requirements.txt @@ -0,0 +1,13 @@ +asgiref==3.8.1 +Deprecated==1.2.14 +iniconfig==2.0.0 +packaging==24.0 +pluggy==1.6.0 +py-cpuinfo==9.0.0 +pytest==7.4.4 +tomli==2.0.1 +typing_extensions==4.12.2 +wrapt==1.16.0 +zipp==3.19.2 +-e opentelemetry-instrumentation +-e instrumentation/opentelemetry-instrumentation-exceptions diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py new file mode 100644 index 0000000000..0c26a6dac6 --- /dev/null +++ b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py @@ -0,0 +1,239 @@ +# 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. + +from __future__ import annotations + +import asyncio +import sys +import threading +from collections.abc import Generator + +import pytest + +import opentelemetry._logs._internal +from opentelemetry._logs import ( + SeverityNumber, + get_logger_provider, + set_logger_provider, +) +from opentelemetry.instrumentation.exceptions import ( + UnhandledExceptionInstrumentor, +) +from opentelemetry.sdk._logs import LoggerProvider +from opentelemetry.semconv.attributes import exception_attributes +from opentelemetry.util._once import Once + +try: + from opentelemetry.sdk._logs.export import ( + InMemoryLogRecordExporter, + SimpleLogRecordProcessor, + ) +except ImportError: + from opentelemetry.sdk._logs.export import ( + InMemoryLogExporter as InMemoryLogRecordExporter, + ) + from opentelemetry.sdk._logs.export import SimpleLogRecordProcessor + +# pylint: disable=redefined-outer-name + + +@pytest.fixture +def log_exporter() -> Generator[InMemoryLogRecordExporter, None, None]: + snapshot = get_logger_provider() + opentelemetry._logs._internal._LOGGER_PROVIDER_SET_ONCE = Once() + provider = LoggerProvider() + exporter = InMemoryLogRecordExporter() + provider.add_log_record_processor(SimpleLogRecordProcessor(exporter)) + set_logger_provider(provider) + try: + yield exporter + finally: + opentelemetry._logs._internal._LOGGER_PROVIDER_SET_ONCE = Once() + set_logger_provider(snapshot) + + +@pytest.fixture +def instrumentor() -> Generator[UnhandledExceptionInstrumentor, None, None]: + inst = UnhandledExceptionInstrumentor() + try: + yield inst + finally: + inst.uninstrument() + + +def _raised_value_error() -> ValueError: + try: + raise ValueError("boom") + except ValueError as exc: + return exc + + +def _finished_log(log_exporter: InMemoryLogRecordExporter): + logs = log_exporter.get_finished_logs() + assert len(logs) == 1 + return logs[0].log_record + + +def test_sys_excepthook_emits_log( + log_exporter: InMemoryLogRecordExporter, + monkeypatch: pytest.MonkeyPatch, + instrumentor: UnhandledExceptionInstrumentor, +) -> None: + called = {"value": False} + + def stub_excepthook(exc_type, exc, tb) -> None: + called["value"] = True + + monkeypatch.setattr(sys, "excepthook", stub_excepthook) + instrumentor.instrument() + + exc = _raised_value_error() + sys.excepthook(type(exc), exc, exc.__traceback__) + + log_record = _finished_log(log_exporter) + assert log_record.severity_text == "FATAL" + assert log_record.severity_number == SeverityNumber.FATAL + assert log_record.body == "boom" + assert called["value"] is True + + attributes = log_record.attributes + assert attributes[exception_attributes.EXCEPTION_TYPE] == "ValueError" + assert isinstance(attributes[exception_attributes.EXCEPTION_TYPE], str) + assert attributes[exception_attributes.EXCEPTION_MESSAGE] == "boom" + assert isinstance(attributes[exception_attributes.EXCEPTION_MESSAGE], str) + assert "ValueError: boom" in attributes[ + exception_attributes.EXCEPTION_STACKTRACE + ] + assert isinstance( + attributes[exception_attributes.EXCEPTION_STACKTRACE], str + ) + + +def test_threading_excepthook_emits_log( + log_exporter: InMemoryLogRecordExporter, + monkeypatch: pytest.MonkeyPatch, + instrumentor: UnhandledExceptionInstrumentor, +) -> None: + called = {"value": False} + + def stub_threading_excepthook(args: threading.ExceptHookArgs) -> None: + called["value"] = True + + monkeypatch.setattr(threading, "excepthook", stub_threading_excepthook) + instrumentor.instrument() + + exc = _raised_value_error() + args = threading.ExceptHookArgs( + (type(exc), exc, exc.__traceback__, threading.current_thread()) + ) + threading.excepthook(args) + + log_record = _finished_log(log_exporter) + assert log_record.severity_text == "ERROR" + assert log_record.severity_number == SeverityNumber.ERROR + assert log_record.body == "boom" + assert called["value"] is True + + attributes = log_record.attributes + assert attributes[exception_attributes.EXCEPTION_TYPE] == "ValueError" + assert attributes[exception_attributes.EXCEPTION_MESSAGE] == "boom" + assert "ValueError: boom" in attributes[ + exception_attributes.EXCEPTION_STACKTRACE + ] + + +def test_asyncio_unhandled_exception_emits_log( + log_exporter: InMemoryLogRecordExporter, + monkeypatch: pytest.MonkeyPatch, + instrumentor: UnhandledExceptionInstrumentor, +) -> None: + called = {"value": False} + + original_handler = asyncio.BaseEventLoop.call_exception_handler + + def stub_call_exception_handler(loop, context) -> None: + called["value"] = True + original_handler(loop, context) + + monkeypatch.setattr( + asyncio.BaseEventLoop, + "call_exception_handler", + stub_call_exception_handler, + ) + instrumentor.instrument() + + loop = asyncio.new_event_loop() + loop.set_exception_handler(lambda _loop, _context: None) + try: + exc = _raised_value_error() + loop.call_exception_handler({"exception": exc, "message": "boom"}) + finally: + loop.close() + + log_record = _finished_log(log_exporter) + assert log_record.severity_text == "ERROR" + assert log_record.severity_number == SeverityNumber.ERROR + assert log_record.body == "boom" + assert called["value"] is True + + attributes = log_record.attributes + assert attributes[exception_attributes.EXCEPTION_TYPE] == "ValueError" + assert attributes[exception_attributes.EXCEPTION_MESSAGE] == "boom" + assert "ValueError: boom" in attributes[ + exception_attributes.EXCEPTION_STACKTRACE + ] + + +def test_base_exceptions_are_not_emitted( + log_exporter: InMemoryLogRecordExporter, + monkeypatch: pytest.MonkeyPatch, + instrumentor: UnhandledExceptionInstrumentor, +) -> None: + called = {"value": False} + + def stub_excepthook(exc_type, exc, tb) -> None: + called["value"] = True + + monkeypatch.setattr(sys, "excepthook", stub_excepthook) + instrumentor.instrument() + + exc = KeyboardInterrupt() + sys.excepthook(type(exc), exc, exc.__traceback__) + + assert not log_exporter.get_finished_logs() + assert called["value"] is True + + +def test_uninstrument_restores_hooks( + monkeypatch: pytest.MonkeyPatch, +) -> None: + instrumentor = UnhandledExceptionInstrumentor() + original_sys = object() + original_threading = object() + original_asyncio = object() + + monkeypatch.setattr(sys, "excepthook", original_sys) + monkeypatch.setattr(threading, "excepthook", original_threading) + monkeypatch.setattr( + asyncio.BaseEventLoop, + "call_exception_handler", + original_asyncio, + ) + + instrumentor.instrument(logger_provider=LoggerProvider()) + instrumentor.uninstrument() + + assert sys.excepthook is original_sys + assert threading.excepthook is original_threading + assert asyncio.BaseEventLoop.call_exception_handler is original_asyncio diff --git a/opentelemetry-contrib-instrumentations/pyproject.toml b/opentelemetry-contrib-instrumentations/pyproject.toml index 630509a4b2..3ba7ea0501 100644 --- a/opentelemetry-contrib-instrumentations/pyproject.toml +++ b/opentelemetry-contrib-instrumentations/pyproject.toml @@ -48,6 +48,7 @@ dependencies = [ "opentelemetry-instrumentation-dbapi==0.63b0.dev", "opentelemetry-instrumentation-django==0.63b0.dev", "opentelemetry-instrumentation-elasticsearch==0.63b0.dev", + "opentelemetry-instrumentation-exceptions==0.63b0.dev", "opentelemetry-instrumentation-falcon==0.63b0.dev", "opentelemetry-instrumentation-fastapi==0.63b0.dev", "opentelemetry-instrumentation-flask==0.63b0.dev", diff --git a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py index 999181bd9f..8be6eecf5d 100644 --- a/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py +++ b/opentelemetry-instrumentation/src/opentelemetry/instrumentation/bootstrap_gen.py @@ -216,6 +216,7 @@ default_instrumentations = [ "opentelemetry-instrumentation-asyncio==0.63b0.dev", "opentelemetry-instrumentation-dbapi==0.63b0.dev", + "opentelemetry-instrumentation-exceptions==0.63b0.dev", "opentelemetry-instrumentation-logging==0.63b0.dev", "opentelemetry-instrumentation-sqlite3==0.63b0.dev", "opentelemetry-instrumentation-threading==0.63b0.dev", diff --git a/tox.ini b/tox.ini index 1f2ca7f8e9..e236adbf64 100644 --- a/tox.ini +++ b/tox.ini @@ -205,6 +205,11 @@ envlist = lint-instrumentation-logging benchmark-instrumentation-logging + ; opentelemetry-instrumentation-exceptions + py3{10,11,12,13,14}-test-instrumentation-exceptions + pypy3-test-instrumentation-exceptions + lint-instrumentation-exceptions + ; opentelemetry-exporter-richconsole py3{10,11,12,13,14}-test-exporter-richconsole pypy3-test-exporter-richconsole @@ -695,6 +700,9 @@ deps = logging: -r {toxinidir}/instrumentation/opentelemetry-instrumentation-logging/test-requirements.txt benchmark-instrumentation-logging: -r {toxinidir}/instrumentation/opentelemetry-instrumentation-logging/benchmark-requirements.txt + exceptions: {[testenv]test_deps} + exceptions: -r {toxinidir}/instrumentation/opentelemetry-instrumentation-exceptions/test-requirements.txt + aiohttp-client: {[testenv]test_deps} aiohttp-client: -r {toxinidir}/instrumentation/opentelemetry-instrumentation-aiohttp-client/test-requirements.txt @@ -897,6 +905,9 @@ commands = lint-instrumentation-logging: sh -c "cd instrumentation && pylint --rcfile ../.pylintrc opentelemetry-instrumentation-logging" benchmark-instrumentation-logging: pytest {toxinidir}/instrumentation/opentelemetry-instrumentation-logging/benchmarks {posargs} --benchmark-json=instrumentation-logging-benchmark.json + test-instrumentation-exceptions: pytest {toxinidir}/instrumentation/opentelemetry-instrumentation-exceptions/tests {posargs} + lint-instrumentation-exceptions: sh -c "cd instrumentation && pylint --rcfile ../.pylintrc opentelemetry-instrumentation-exceptions" + test-instrumentation-mysql: pytest {toxinidir}/instrumentation/opentelemetry-instrumentation-mysql/tests {posargs} lint-instrumentation-mysql: sh -c "cd instrumentation && pylint --rcfile ../.pylintrc opentelemetry-instrumentation-mysql" From 162749818f7e415529cc2ab5b6c333bf80e2c087 Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Mon, 4 May 2026 15:37:03 +0200 Subject: [PATCH 02/12] Fix lint Signed-off-by: Israel Blancas --- .../instrumentation/exceptions/__init__.py | 10 +++++++-- .../tests/test_exceptions.py | 21 +++++++++++-------- uv.lock | 18 ++++++++++++++++ 3 files changed, 38 insertions(+), 11 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py index c5495f07d5..40dae927a4 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py @@ -113,7 +113,10 @@ def _handle_sys_exc( exc: BaseException, tb: TracebackType | None, ) -> None: - if isinstance(exc, Exception) and self._exception_logger is not None: + if ( + isinstance(exc, Exception) + and self._exception_logger is not None + ): try: self._exception_logger.emit( exc, @@ -182,7 +185,10 @@ def _call_exception_handler( context: dict[str, Any], ) -> None: exc = context.get("exception") - if isinstance(exc, Exception) and self._exception_logger is not None: + if ( + isinstance(exc, Exception) + and self._exception_logger is not None + ): try: self._exception_logger.emit( exc, diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py index 0c26a6dac6..78b231a462 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py @@ -112,9 +112,10 @@ def stub_excepthook(exc_type, exc, tb) -> None: assert isinstance(attributes[exception_attributes.EXCEPTION_TYPE], str) assert attributes[exception_attributes.EXCEPTION_MESSAGE] == "boom" assert isinstance(attributes[exception_attributes.EXCEPTION_MESSAGE], str) - assert "ValueError: boom" in attributes[ - exception_attributes.EXCEPTION_STACKTRACE - ] + assert ( + "ValueError: boom" + in attributes[exception_attributes.EXCEPTION_STACKTRACE] + ) assert isinstance( attributes[exception_attributes.EXCEPTION_STACKTRACE], str ) @@ -148,9 +149,10 @@ def stub_threading_excepthook(args: threading.ExceptHookArgs) -> None: attributes = log_record.attributes assert attributes[exception_attributes.EXCEPTION_TYPE] == "ValueError" assert attributes[exception_attributes.EXCEPTION_MESSAGE] == "boom" - assert "ValueError: boom" in attributes[ - exception_attributes.EXCEPTION_STACKTRACE - ] + assert ( + "ValueError: boom" + in attributes[exception_attributes.EXCEPTION_STACKTRACE] + ) def test_asyncio_unhandled_exception_emits_log( @@ -190,9 +192,10 @@ def stub_call_exception_handler(loop, context) -> None: attributes = log_record.attributes assert attributes[exception_attributes.EXCEPTION_TYPE] == "ValueError" assert attributes[exception_attributes.EXCEPTION_MESSAGE] == "boom" - assert "ValueError: boom" in attributes[ - exception_attributes.EXCEPTION_STACKTRACE - ] + assert ( + "ValueError: boom" + in attributes[exception_attributes.EXCEPTION_STACKTRACE] + ) def test_base_exceptions_are_not_emitted( diff --git a/uv.lock b/uv.lock index 14d5ea35b6..8d0e824c7b 100644 --- a/uv.lock +++ b/uv.lock @@ -37,6 +37,7 @@ members = [ "opentelemetry-instrumentation-dbapi", "opentelemetry-instrumentation-django", "opentelemetry-instrumentation-elasticsearch", + "opentelemetry-instrumentation-exceptions", "opentelemetry-instrumentation-falcon", "opentelemetry-instrumentation-fastapi", "opentelemetry-instrumentation-flask", @@ -3315,6 +3316,23 @@ requires-dist = [ ] provides-extras = ["instruments"] +[[package]] +name = "opentelemetry-instrumentation-exceptions" +source = { editable = "instrumentation/opentelemetry-instrumentation-exceptions" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, + { name = "opentelemetry-semantic-conventions" }, +] + +[package.metadata] +requires-dist = [ + { name = "opentelemetry-api", git = "https://github.com/open-telemetry/opentelemetry-python?subdirectory=opentelemetry-api&branch=main" }, + { name = "opentelemetry-instrumentation", editable = "opentelemetry-instrumentation" }, + { name = "opentelemetry-semantic-conventions", git = "https://github.com/open-telemetry/opentelemetry-python?subdirectory=opentelemetry-semantic-conventions&branch=main" }, +] +provides-extras = ["instruments"] + [[package]] name = "opentelemetry-instrumentation-falcon" source = { editable = "instrumentation/opentelemetry-instrumentation-falcon" } From 08536ed07c4d2a3e7aa374f4252b0d439ad0be3c Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Mon, 4 May 2026 15:46:59 +0200 Subject: [PATCH 03/12] Fix lint Signed-off-by: Israel Blancas --- .../opentelemetry-instrumentation-exceptions/README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/README.rst b/instrumentation/opentelemetry-instrumentation-exceptions/README.rst index 0fb4ada53c..59e52bde58 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/README.rst +++ b/instrumentation/opentelemetry-instrumentation-exceptions/README.rst @@ -31,5 +31,5 @@ logs. References ---------- -* `OpenTelemetry unhandled exceptions instrumentation `_ +* `OpenTelemetry unhandled exceptions instrumentation source `_ * `OpenTelemetry Project `_ From 480a2b427660db7c7fcbf1c7c953b220ec62467a Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Mon, 4 May 2026 16:08:27 +0200 Subject: [PATCH 04/12] Fix lint Signed-off-by: Israel Blancas --- .../opentelemetry-instrumentation-exceptions/README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/README.rst b/instrumentation/opentelemetry-instrumentation-exceptions/README.rst index 59e52bde58..f73f1af236 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/README.rst +++ b/instrumentation/opentelemetry-instrumentation-exceptions/README.rst @@ -31,5 +31,5 @@ logs. References ---------- -* `OpenTelemetry unhandled exceptions instrumentation source `_ +* `OpenTelemetry Python Contrib repository `_ * `OpenTelemetry Project `_ From 331b01a10a42d5462532656fb6e041d81574f03c Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Tue, 5 May 2026 09:34:53 +0200 Subject: [PATCH 05/12] Apply changes requested in code review Signed-off-by: Israel Blancas --- .../instrumentation/exceptions/__init__.py | 208 ++++++++---------- .../tests/test_exceptions.py | 12 +- 2 files changed, 106 insertions(+), 114 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py index 40dae927a4..60135adc9b 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py @@ -37,17 +37,22 @@ import threading from collections.abc import Collection from types import TracebackType -from typing import Any, Callable +from typing import Any -from opentelemetry._logs import SeverityNumber, get_logger +from wrapt import ( + wrap_function_wrapper, # type: ignore[reportUnknownVariableType] +) + +from opentelemetry._logs import LoggerProvider, SeverityNumber, get_logger from opentelemetry.instrumentation.exceptions.package import _instruments from opentelemetry.instrumentation.exceptions.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor +from opentelemetry.instrumentation.utils import unwrap from opentelemetry.semconv.schemas import Schemas class _ExceptionLogger: - def __init__(self, logger_provider: Any = None): + def __init__(self, logger_provider: LoggerProvider | None = None): self._logger = get_logger( __name__, __version__, @@ -73,18 +78,10 @@ def emit( class UnhandledExceptionInstrumentor(BaseInstrumentor): """Emit logs for uncaught exceptions and unhandled asyncio exceptions.""" - def __init__(self, logger_provider: Any = None): + def __init__(self, logger_provider: LoggerProvider | None = None): super().__init__() self._logger_provider = logger_provider self._exception_logger: _ExceptionLogger | None = None - self._original_sys_excepthook: Callable[..., Any] | None = None - self._original_threading_excepthook: Callable[..., Any] | None = None - self._original_asyncio_call_exception_handler: ( - Callable[..., Any] | None - ) = None - self._sys_excepthook: Callable[..., Any] | None = None - self._threading_excepthook: Callable[..., Any] | None = None - self._asyncio_call_exception_handler: Callable[..., Any] | None = None def instrumentation_dependencies(self) -> Collection[str]: return _instruments @@ -103,116 +100,105 @@ def _uninstrument(self, **kwargs: Any): self._exception_logger = None def _install_sys_hook(self) -> None: - if self._original_sys_excepthook is not None: - return + wrap_function_wrapper( + sys, + "excepthook", + self._wrap_sys_excepthook, + ) - self._original_sys_excepthook = sys.excepthook - - def _handle_sys_exc( - exc_type: type[BaseException], - exc: BaseException, - tb: TracebackType | None, - ) -> None: - if ( - isinstance(exc, Exception) - and self._exception_logger is not None - ): - try: - self._exception_logger.emit( - exc, - severity_text="FATAL", - severity_number=SeverityNumber.FATAL, - ) - except Exception: # pragma: no cover # pylint: disable=broad-exception-caught - pass - self._original_sys_excepthook(exc_type, exc, tb) - - self._sys_excepthook = _handle_sys_exc - sys.excepthook = _handle_sys_exc - - def _restore_sys_hook(self) -> None: - if ( - self._original_sys_excepthook is not None - and sys.excepthook is self._sys_excepthook - ): - sys.excepthook = self._original_sys_excepthook - self._original_sys_excepthook = None - self._sys_excepthook = None + @staticmethod + def _restore_sys_hook() -> None: + unwrap(sys, "excepthook") def _install_threading_hook(self) -> None: - if self._original_threading_excepthook is not None: - return + wrap_function_wrapper( + threading, + "excepthook", + self._wrap_threading_excepthook, + ) - self._original_threading_excepthook = threading.excepthook - - def _handle_threading_exc(args: threading.ExceptHookArgs) -> None: - if ( - isinstance(args.exc_value, Exception) - and self._exception_logger is not None - ): - try: - self._exception_logger.emit( - args.exc_value, - severity_text="ERROR", - severity_number=SeverityNumber.ERROR, - ) - except Exception: # pragma: no cover # pylint: disable=broad-exception-caught - pass - self._original_threading_excepthook(args) - - self._threading_excepthook = _handle_threading_exc - threading.excepthook = _handle_threading_exc - - def _restore_threading_hook(self) -> None: - if ( - self._original_threading_excepthook is not None - and threading.excepthook is self._threading_excepthook - ): - threading.excepthook = self._original_threading_excepthook - self._original_threading_excepthook = None - self._threading_excepthook = None + @staticmethod + def _restore_threading_hook() -> None: + unwrap(threading, "excepthook") def _install_asyncio_hook(self) -> None: - if self._original_asyncio_call_exception_handler is not None: + wrap_function_wrapper( + asyncio.BaseEventLoop, + "call_exception_handler", + self._wrap_asyncio_call_exception_handler, + ) + + @staticmethod + def _restore_asyncio_hook() -> None: + unwrap(asyncio.BaseEventLoop, "call_exception_handler") + + def _emit_exception( + self, + exc: BaseException, + *, + severity_text: str, + severity_number: SeverityNumber, + ) -> None: + if not isinstance(exc, Exception) or self._exception_logger is None: return - self._original_asyncio_call_exception_handler = ( - asyncio.BaseEventLoop.call_exception_handler + try: + self._exception_logger.emit( + exc, + severity_text=severity_text, + severity_number=severity_number, + ) + except ( + Exception + ): # pragma: no cover # pylint: disable=broad-exception-caught + pass + + def _wrap_sys_excepthook( + self, + wrapped, + instance, + args: tuple[type[BaseException], BaseException, TracebackType | None], + kwargs: dict[str, Any], + ) -> None: + _, exc, _ = args + self._emit_exception( + exc, + severity_text="FATAL", + severity_number=SeverityNumber.FATAL, ) + wrapped(*args, **kwargs) - def _call_exception_handler( - loop: asyncio.AbstractEventLoop, - context: dict[str, Any], - ) -> None: - exc = context.get("exception") - if ( - isinstance(exc, Exception) - and self._exception_logger is not None - ): - try: - self._exception_logger.emit( - exc, - severity_text="ERROR", - severity_number=SeverityNumber.ERROR, - ) - except Exception: # pragma: no cover # pylint: disable=broad-exception-caught - pass - self._original_asyncio_call_exception_handler(loop, context) - - self._asyncio_call_exception_handler = _call_exception_handler - asyncio.BaseEventLoop.call_exception_handler = _call_exception_handler - - def _restore_asyncio_hook(self) -> None: - if ( - self._original_asyncio_call_exception_handler is not None - and asyncio.BaseEventLoop.call_exception_handler - is self._asyncio_call_exception_handler - ): - asyncio.BaseEventLoop.call_exception_handler = ( - self._original_asyncio_call_exception_handler + def _wrap_threading_excepthook( + self, + wrapped, + instance, + args: tuple[threading.ExceptHookArgs], + kwargs: dict[str, Any], + ) -> None: + (hook_args,) = args + self._emit_exception( + hook_args.exc_value, + severity_text="ERROR", + severity_number=SeverityNumber.ERROR, + ) + wrapped(*args, **kwargs) + + def _wrap_asyncio_call_exception_handler( + self, + wrapped, + instance: asyncio.AbstractEventLoop, + args: tuple[dict[str, Any]], + kwargs: dict[str, Any], + ) -> None: + (context,) = args + exc = context.get("exception") + if isinstance(exc, BaseException): + self._emit_exception( + exc, + severity_text="ERROR", + severity_number=SeverityNumber.ERROR, ) - self._original_asyncio_call_exception_handler = None - self._asyncio_call_exception_handler = None + wrapped(*args, **kwargs) __all__ = ["UnhandledExceptionInstrumentor"] diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py index 78b231a462..d78fcc986e 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py @@ -222,9 +222,15 @@ def test_uninstrument_restores_hooks( monkeypatch: pytest.MonkeyPatch, ) -> None: instrumentor = UnhandledExceptionInstrumentor() - original_sys = object() - original_threading = object() - original_asyncio = object() + + def original_sys(exc_type, exc, tb) -> None: + del exc_type, exc, tb + + def original_threading(args: threading.ExceptHookArgs) -> None: + del args + + def original_asyncio(loop, context) -> None: + del loop, context monkeypatch.setattr(sys, "excepthook", original_sys) monkeypatch.setattr(threading, "excepthook", original_threading) From a55e03cab566e447ba20646fc59341e6552c354f Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Tue, 5 May 2026 09:40:09 +0200 Subject: [PATCH 06/12] Fix ci Signed-off-by: Israel Blancas --- .../opentelemetry/instrumentation/exceptions/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py index 60135adc9b..e019425f33 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py @@ -148,9 +148,9 @@ def _emit_exception( severity_text=severity_text, severity_number=severity_number, ) - except ( - Exception - ): # pragma: no cover # pylint: disable=broad-exception-caught + # Logging must never replace the original unhandled exception path. + # pylint: disable-next=broad-exception-caught + except Exception: # pragma: no cover pass def _wrap_sys_excepthook( From 980a0af536a0c6c8590dee4927906cabda03036f Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Tue, 12 May 2026 12:06:25 +0200 Subject: [PATCH 07/12] Fix lint Signed-off-by: Israel Blancas --- .../instrumentation/exceptions/__init__.py | 13 +------------ .../instrumentation/exceptions/package.py | 13 +------------ .../instrumentation/exceptions/version.py | 13 +------------ .../tests/test_exceptions.py | 13 +------------ 4 files changed, 4 insertions(+), 48 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py index e019425f33..190f8db1bd 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py @@ -1,16 +1,5 @@ # 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. +# SPDX-License-Identifier: Apache-2.0 """ Instrument uncaught exceptions to emit OpenTelemetry logs. diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/package.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/package.py index 1bf177779b..68cc3b4463 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/package.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/package.py @@ -1,16 +1,5 @@ # 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. +# SPDX-License-Identifier: Apache-2.0 _instruments = () diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/version.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/version.py index a07bc2663e..716ad67f7d 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/version.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/version.py @@ -1,15 +1,4 @@ # 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. +# SPDX-License-Identifier: Apache-2.0 __version__ = "0.63b0.dev" diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py index d78fcc986e..84694783ed 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py @@ -1,16 +1,5 @@ # 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. +# SPDX-License-Identifier: Apache-2.0 from __future__ import annotations From 90de38d85a941991e14994a24f7fbc0efc041cc7 Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Wed, 13 May 2026 12:01:29 +0200 Subject: [PATCH 08/12] Fix changelog Signed-off-by: Israel Blancas --- .changelog/4503.added | 1 + CHANGELOG.md | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) create mode 100644 .changelog/4503.added diff --git a/.changelog/4503.added b/.changelog/4503.added new file mode 100644 index 0000000000..bb112e00ba --- /dev/null +++ b/.changelog/4503.added @@ -0,0 +1 @@ +`opentelemetry-instrumentation-exceptions`: add instrumentation to emit OpenTelemetry logs for uncaught process, thread, and asyncio exceptions. diff --git a/CHANGELOG.md b/CHANGELOG.md index 2454e0c868..6448b92374 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,8 +25,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#4335](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4335)) - Expand `AGENTS.md` with instrumentation/GenAI guidance and add PR review instructions. ([#4457](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4457)) -- `opentelemetry-instrumentation-exceptions`: Add instrumentation to emit OpenTelemetry logs for uncaught exceptions, uncaught thread exceptions, and unhandled asyncio task exceptions. - ([#4209](https://github.com/open-telemetry/opentelemetry-python-contrib/issues/4209)) - `opentelemetry-instrumentation-logging`: Add `OTEL_PYTHON_LOG_HANDLER_LEVEL` and `OTEL_PYTHON_LOG_FORMAT` environment variables to configure the log level and formatter of the auto-instrumented `LoggingHandler`. ([#4298](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4298)) - Remove redundant `pylint: disable=attribute-defined-outside-init` comments and add rule to global `.pylintrc` disable list From 9c0cafa31fd9b4eecb4d2eef07eb20132ca2f37e Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Wed, 17 Jun 2026 12:19:51 +0200 Subject: [PATCH 09/12] Apply changes in code review Signed-off-by: Israel Blancas --- .../instrumentation/exceptions/__init__.py | 8 ++++++++ .../tests/test_exceptions.py | 20 ++++++++----------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py index b5c795fa05..82ee5cd46a 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py @@ -55,8 +55,10 @@ def emit( *, severity_text: str, severity_number: SeverityNumber, + event_name: str, ) -> None: self._logger.emit( + event_name=event_name, body=str(exc), severity_text=severity_text, severity_number=severity_number, @@ -128,7 +130,9 @@ def _emit_exception( *, severity_text: str, severity_number: SeverityNumber, + event_name: str, ) -> None: + # BaseException includes process-control signals like KeyboardInterrupt. if not isinstance(exc, Exception) or self._exception_logger is None: return @@ -137,6 +141,7 @@ def _emit_exception( exc, severity_text=severity_text, severity_number=severity_number, + event_name=event_name, ) # Logging must never replace the original unhandled exception path. # pylint: disable-next=broad-exception-caught @@ -155,6 +160,7 @@ def _wrap_sys_excepthook( exc, severity_text="FATAL", severity_number=SeverityNumber.FATAL, + event_name=type(exc).__name__, ) wrapped(*args, **kwargs) @@ -170,6 +176,7 @@ def _wrap_threading_excepthook( hook_args.exc_value, severity_text="ERROR", severity_number=SeverityNumber.ERROR, + event_name=hook_args.exc_type.__name__, ) wrapped(*args, **kwargs) @@ -187,6 +194,7 @@ def _wrap_asyncio_call_exception_handler( exc, severity_text="ERROR", severity_number=SeverityNumber.ERROR, + event_name=context.get("message", type(exc).__name__), ) wrapped(*args, **kwargs) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py index 84694783ed..2f9500beb5 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py @@ -20,20 +20,13 @@ UnhandledExceptionInstrumentor, ) from opentelemetry.sdk._logs import LoggerProvider +from opentelemetry.sdk._logs.export import ( + InMemoryLogRecordExporter, + SimpleLogRecordProcessor, +) from opentelemetry.semconv.attributes import exception_attributes from opentelemetry.util._once import Once -try: - from opentelemetry.sdk._logs.export import ( - InMemoryLogRecordExporter, - SimpleLogRecordProcessor, - ) -except ImportError: - from opentelemetry.sdk._logs.export import ( - InMemoryLogExporter as InMemoryLogRecordExporter, - ) - from opentelemetry.sdk._logs.export import SimpleLogRecordProcessor - # pylint: disable=redefined-outer-name @@ -93,6 +86,7 @@ def stub_excepthook(exc_type, exc, tb) -> None: log_record = _finished_log(log_exporter) assert log_record.severity_text == "FATAL" assert log_record.severity_number == SeverityNumber.FATAL + assert log_record.event_name == "ValueError" assert log_record.body == "boom" assert called["value"] is True @@ -132,6 +126,7 @@ def stub_threading_excepthook(args: threading.ExceptHookArgs) -> None: log_record = _finished_log(log_exporter) assert log_record.severity_text == "ERROR" assert log_record.severity_number == SeverityNumber.ERROR + assert log_record.event_name == "ValueError" assert log_record.body == "boom" assert called["value"] is True @@ -168,13 +163,14 @@ def stub_call_exception_handler(loop, context) -> None: loop.set_exception_handler(lambda _loop, _context: None) try: exc = _raised_value_error() - loop.call_exception_handler({"exception": exc, "message": "boom"}) + loop.call_exception_handler({"exception": exc, "message": "task boom"}) finally: loop.close() log_record = _finished_log(log_exporter) assert log_record.severity_text == "ERROR" assert log_record.severity_number == SeverityNumber.ERROR + assert log_record.event_name == "task boom" assert log_record.body == "boom" assert called["value"] is True From c2b31e342297236c3516985eaa927661683800c1 Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Wed, 17 Jun 2026 16:00:53 +0200 Subject: [PATCH 10/12] Fix ci Signed-off-by: Israel Blancas --- .../src/opentelemetry/instrumentation/vertexai/patch.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/instrumentation-genai/opentelemetry-instrumentation-vertexai/src/opentelemetry/instrumentation/vertexai/patch.py b/instrumentation-genai/opentelemetry-instrumentation-vertexai/src/opentelemetry/instrumentation/vertexai/patch.py index a1c2cac903..0db62e0ed4 100644 --- a/instrumentation-genai/opentelemetry-instrumentation-vertexai/src/opentelemetry/instrumentation/vertexai/patch.py +++ b/instrumentation-genai/opentelemetry-instrumentation-vertexai/src/opentelemetry/instrumentation/vertexai/patch.py @@ -162,7 +162,7 @@ def handle_response( | None, ) -> None: attributes = ( - get_server_attributes(instance.api_endpoint) # type: ignore[reportUnknownMemberType] + get_server_attributes(instance.api_endpoint) | request_attributes | get_genai_response_attributes(response) ) @@ -246,7 +246,7 @@ def _with_default_instrumentation( kwargs: Any, ): params = _extract_params(*args, **kwargs) - api_endpoint: str = instance.api_endpoint # type: ignore[reportUnknownMemberType] + api_endpoint: str = instance.api_endpoint span_attributes = { **get_genai_request_attributes(False, params), **get_server_attributes(api_endpoint), From 015231a1ad8a4a8738930e0787b8600e998cbe9f Mon Sep 17 00:00:00 2001 From: Israel Blancas Date: Thu, 18 Jun 2026 13:25:55 +0200 Subject: [PATCH 11/12] Address changes requested in code review Signed-off-by: Israel Blancas --- .../LICENSE | 214 ++++++++++++++++-- .../instrumentation/exceptions/__init__.py | 59 ++--- .../tests/test_exceptions.py | 45 ++++ 3 files changed, 265 insertions(+), 53 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/LICENSE b/instrumentation/opentelemetry-instrumentation-exceptions/LICENSE index b0a6f42841..261eeb9e9f 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/LICENSE +++ b/instrumentation/opentelemetry-instrumentation-exceptions/LICENSE @@ -1,13 +1,201 @@ -# 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. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py index 82ee5cd46a..49d6656ff0 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py @@ -32,7 +32,7 @@ wrap_function_wrapper, # type: ignore[reportUnknownVariableType] ) -from opentelemetry._logs import LoggerProvider, SeverityNumber, get_logger +from opentelemetry._logs import Logger, SeverityNumber, get_logger from opentelemetry.instrumentation.exceptions.package import _instruments from opentelemetry.instrumentation.exceptions.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor @@ -40,47 +40,24 @@ from opentelemetry.semconv.schemas import Schemas -class _ExceptionLogger: - def __init__(self, logger_provider: LoggerProvider | None = None): - self._logger = get_logger( - __name__, - __version__, - logger_provider, - schema_url=Schemas.V1_37_0.value, - ) - - def emit( - self, - exc: Exception, - *, - severity_text: str, - severity_number: SeverityNumber, - event_name: str, - ) -> None: - self._logger.emit( - event_name=event_name, - body=str(exc), - severity_text=severity_text, - severity_number=severity_number, - exception=exc, - ) - - class UnhandledExceptionInstrumentor(BaseInstrumentor): """Emit logs for uncaught exceptions and unhandled asyncio exceptions.""" - def __init__(self, logger_provider: LoggerProvider | None = None): + def __init__(self): super().__init__() - self._logger_provider = logger_provider - self._exception_logger: _ExceptionLogger | None = None - self._instrumentation_dependencies = _instruments + self._logger: Logger | None = None + # pylint: disable-next=no-self-use def instrumentation_dependencies(self) -> Collection[str]: - return self._instrumentation_dependencies + return _instruments def _instrument(self, **kwargs: Any): - logger_provider = kwargs.get("logger_provider", self._logger_provider) - self._exception_logger = _ExceptionLogger(logger_provider) + self._logger = get_logger( + __name__, + __version__, + kwargs.get("logger_provider"), + schema_url=Schemas.V1_37_0.value, + ) self._install_sys_hook() self._install_threading_hook() self._install_asyncio_hook() @@ -89,7 +66,7 @@ def _uninstrument(self, **kwargs: Any): self._restore_sys_hook() self._restore_threading_hook() self._restore_asyncio_hook() - self._exception_logger = None + self._logger = None def _install_sys_hook(self) -> None: wrap_function_wrapper( @@ -133,15 +110,16 @@ def _emit_exception( event_name: str, ) -> None: # BaseException includes process-control signals like KeyboardInterrupt. - if not isinstance(exc, Exception) or self._exception_logger is None: + if not isinstance(exc, Exception) or self._logger is None: return try: - self._exception_logger.emit( - exc, + self._logger.emit( + event_name=event_name, + body=str(exc), severity_text=severity_text, severity_number=severity_number, - event_name=event_name, + exception=exc, ) # Logging must never replace the original unhandled exception path. # pylint: disable-next=broad-exception-caught @@ -190,11 +168,12 @@ def _wrap_asyncio_call_exception_handler( (context,) = args exc = context.get("exception") if isinstance(exc, BaseException): + message = context.get("message") self._emit_exception( exc, severity_text="ERROR", severity_number=SeverityNumber.ERROR, - event_name=context.get("message", type(exc).__name__), + event_name=str(message) if message else type(exc).__name__, ) wrapped(*args, **kwargs) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py index 2f9500beb5..614fc8e211 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py @@ -183,6 +183,35 @@ def stub_call_exception_handler(loop, context) -> None: ) +@pytest.mark.parametrize( + ("message", "expected_event_name"), + ((None, "ValueError"), (42, "42")), +) +def test_asyncio_event_name_falls_back_or_coerces( + log_exporter: InMemoryLogRecordExporter, + monkeypatch: pytest.MonkeyPatch, + instrumentor: UnhandledExceptionInstrumentor, + message: object, + expected_event_name: str, +) -> None: + monkeypatch.setattr( + asyncio.BaseEventLoop, + "call_exception_handler", + lambda _loop, _context: None, + ) + instrumentor.instrument() + + loop = asyncio.new_event_loop() + loop.set_exception_handler(lambda _loop, _context: None) + try: + exc = _raised_value_error() + loop.call_exception_handler({"exception": exc, "message": message}) + finally: + loop.close() + + assert _finished_log(log_exporter).event_name == expected_event_name + + def test_base_exceptions_are_not_emitted( log_exporter: InMemoryLogRecordExporter, monkeypatch: pytest.MonkeyPatch, @@ -203,6 +232,22 @@ def stub_excepthook(exc_type, exc, tb) -> None: assert called["value"] is True +def test_double_instrument_does_not_emit_duplicate_logs( + log_exporter: InMemoryLogRecordExporter, + monkeypatch: pytest.MonkeyPatch, + instrumentor: UnhandledExceptionInstrumentor, +) -> None: + monkeypatch.setattr(sys, "excepthook", lambda _exc_type, _exc, _tb: None) + + instrumentor.instrument() + instrumentor.instrument() + + exc = _raised_value_error() + sys.excepthook(type(exc), exc, exc.__traceback__) + + assert len(log_exporter.get_finished_logs()) == 1 + + def test_uninstrument_restores_hooks( monkeypatch: pytest.MonkeyPatch, ) -> None: From 93fb3b013e2287d297cc017e722472dbdc93d03b Mon Sep 17 00:00:00 2001 From: Riccardo Magliocchetti Date: Mon, 22 Jun 2026 16:46:24 +0200 Subject: [PATCH 12/12] Make asyncio call_exception_handler wrapper a bit more robust against inputs --- .../instrumentation/exceptions/__init__.py | 21 ++--- .../tests/test_exceptions.py | 79 +++++++++++++++++++ 2 files changed, 90 insertions(+), 10 deletions(-) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py index 49d6656ff0..c16e9f326c 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/src/opentelemetry/instrumentation/exceptions/__init__.py @@ -165,16 +165,17 @@ def _wrap_asyncio_call_exception_handler( args: tuple[dict[str, Any]], kwargs: dict[str, Any], ) -> None: - (context,) = args - exc = context.get("exception") - if isinstance(exc, BaseException): - message = context.get("message") - self._emit_exception( - exc, - severity_text="ERROR", - severity_number=SeverityNumber.ERROR, - event_name=str(message) if message else type(exc).__name__, - ) + context = args[0] if args else kwargs.get("context") + if context: + exc = context.get("exception") + if isinstance(exc, BaseException): + message = context.get("message") + self._emit_exception( + exc, + severity_text="ERROR", + severity_number=SeverityNumber.ERROR, + event_name=str(message) if message else type(exc).__name__, + ) wrapped(*args, **kwargs) diff --git a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py index 614fc8e211..fe1ca0a147 100644 --- a/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py +++ b/instrumentation/opentelemetry-instrumentation-exceptions/tests/test_exceptions.py @@ -183,6 +183,85 @@ def stub_call_exception_handler(loop, context) -> None: ) +def test_asyncio_unhandled_exception_called_with_kwarg_emits_log( + log_exporter: InMemoryLogRecordExporter, + monkeypatch: pytest.MonkeyPatch, + instrumentor: UnhandledExceptionInstrumentor, +) -> None: + called = {"value": False} + + original_handler = asyncio.BaseEventLoop.call_exception_handler + + def stub_call_exception_handler(loop, context) -> None: + called["value"] = True + original_handler(loop, context) + + monkeypatch.setattr( + asyncio.BaseEventLoop, + "call_exception_handler", + stub_call_exception_handler, + ) + instrumentor.instrument() + + loop = asyncio.new_event_loop() + loop.set_exception_handler(lambda _loop, _context: None) + try: + exc = _raised_value_error() + loop.call_exception_handler( + context={"exception": exc, "message": "task boom"} + ) + finally: + loop.close() + + log_record = _finished_log(log_exporter) + assert log_record.severity_text == "ERROR" + assert log_record.severity_number == SeverityNumber.ERROR + assert log_record.event_name == "task boom" + assert log_record.body == "boom" + assert called["value"] is True + + attributes = log_record.attributes + assert attributes[exception_attributes.EXCEPTION_TYPE] == "ValueError" + assert attributes[exception_attributes.EXCEPTION_MESSAGE] == "boom" + assert ( + "ValueError: boom" + in attributes[exception_attributes.EXCEPTION_STACKTRACE] + ) + + +def test_asyncio_unhandled_exception_invalid_call( + log_exporter: InMemoryLogRecordExporter, + monkeypatch: pytest.MonkeyPatch, + instrumentor: UnhandledExceptionInstrumentor, +) -> None: + called = {"value": False} + + original_handler = asyncio.BaseEventLoop.call_exception_handler + + def stub_call_exception_handler(loop, context) -> None: + called["value"] = True + original_handler(loop, context) + + monkeypatch.setattr( + asyncio.BaseEventLoop, + "call_exception_handler", + stub_call_exception_handler, + ) + instrumentor.instrument() + + loop = asyncio.new_event_loop() + loop.set_exception_handler(lambda _loop, _context: None) + try: + _raised_value_error() + with pytest.raises(TypeError): + loop.call_exception_handler() + finally: + loop.close() + + logs = log_exporter.get_finished_logs() + assert not logs + + @pytest.mark.parametrize( ("message", "expected_event_name"), ((None, "ValueError"), (42, "42")),