diff --git a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/diagnostic_logging.py b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/diagnostic_logging.py index b77f3991f579..96f52590f8cb 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/diagnostic_logging.py +++ b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/diagnostic_logging.py @@ -99,7 +99,9 @@ def _initialize(cls): _diagnostic_file_logger.addHandler(f_handler) cls._initialized = True except Exception as e: # pylint: disable=broad-except - _logger.error("Failed to initialize Azure Monitor diagnostic logging: %s", e) + _logger.error( + "Failed to initialize Azure Monitor diagnostic logging: %s", e + ) # pylint: disable=do-not-log-exceptions-if-not-debug cls._initialized = False @classmethod diff --git a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/instrumentation.py b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/instrumentation.py index 06360ad02162..f5a2f9baa322 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/instrumentation.py +++ b/sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_utils/instrumentation.py @@ -92,7 +92,7 @@ def get_dependency_conflicts( try: req = Requirement(dep) except InvalidRequirement as exc: - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug 'error parsing dependency, reporting as a conflict: "%s" - %s', dep, exc, @@ -127,7 +127,7 @@ def _get_dependency_conflicts_any( try: req = Requirement(dep) except InvalidRequirement as exc: - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug 'error parsing dependency, reporting as a conflict: "%s" - %s', dep, exc, diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_managed_credential.py b/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_managed_credential.py index df0574f30d1b..c33b6f4290f9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_managed_credential.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_managed_credential.py @@ -8,11 +8,11 @@ An example to show an application using Opentelemetry tracing api and sdk with a Azure Managed Identity Credential. Credentials are used for Azure Active Directory/EntraId Authentication. """ +from opentelemetry import trace + # You will need to install azure-identity from azure.identity import ManagedIdentityCredential from azure.monitor.opentelemetry import configure_azure_monitor -from opentelemetry import trace - credential = ManagedIdentityCredential(client_id="") configure_azure_monitor( diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_secret_credential.py b/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_secret_credential.py index 45c32d689989..081063b7e952 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_secret_credential.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/authentication/sample_secret_credential.py @@ -8,10 +8,11 @@ An example to show an application using Opentelemetry tracing api and sdk with a Azure Client Secret Credential. Credentials are used for Azure Active Directory/EntraId Authentication. """ +from opentelemetry import trace + # You will need to install azure-identity from azure.identity import ClientSecretCredential from azure.monitor.opentelemetry import configure_azure_monitor -from opentelemetry import trace credential = ClientSecretCredential( tenant_id=" None: + def on_emit(self, log_record: ReadableLogRecord) -> None: current_span = trace.get_current_span() if current_span and getattr(current_span, "name", None): - if readable_log_record.log_record.attributes is None: - readable_log_record.log_record.attributes = {} - readable_log_record.log_record.attributes[ContextTagKeys.AI_OPERATION_NAME] = current_span.name + if log_record.log_record.attributes is None: + log_record.log_record.attributes = {} + log_record.log_record.attributes[ContextTagKeys.AI_OPERATION_NAME] = current_span.name def shutdown(self) -> None: pass diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/attributes.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/attributes.py index 7e676cc2d527..df36f7828670 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/attributes.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/attributes.py @@ -4,8 +4,8 @@ # license information. # -------------------------------------------------------------------------- -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import metrics +from azure.monitor.opentelemetry import configure_azure_monitor # Configure Azure monitor collection telemetry pipeline configure_azure_monitor() diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/instruments.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/instruments.py index 882218981dca..4aca5d348481 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/instruments.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/instruments.py @@ -6,27 +6,26 @@ from typing import Iterable -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import metrics from opentelemetry.metrics import CallbackOptions, Observation -from opentelemetry.sdk.resources import Resource, ResourceAttributes +from azure.monitor.opentelemetry import configure_azure_monitor # Configure Azure monitor collection telemetry pipeline configure_azure_monitor() # Callback functions for observable instruments -def observable_counter_func(options: CallbackOptions) -> Iterable[Observation]: +def observable_counter_func(_options: CallbackOptions) -> Iterable[Observation]: yield Observation(1, {}) def observable_up_down_counter_func( - options: CallbackOptions, + _options: CallbackOptions, ) -> Iterable[Observation]: yield Observation(-10, {}) -def observable_gauge_func(options: CallbackOptions) -> Iterable[Observation]: +def observable_gauge_func(_options: CallbackOptions) -> Iterable[Observation]: yield Observation(9, {}) diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py index 2b6b4e24d1da..479730d39168 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/live_metrics.py @@ -10,12 +10,12 @@ Live metrics is enabled by default, it can be disabled by setting `enable_live_metrics` to `False` """ import logging -import requests # type: ignore[import-untyped] import time +import requests # type: ignore[import-untyped] # pylint: disable=networking-import-outside-azure-core-transport -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace from opentelemetry.sdk.resources import Resource +from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor( resource=Resource.create( diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/modify_metrics.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/modify_metrics.py index ef87c0e4bdac..45793bfa7dbf 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/modify_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/modify_metrics.py @@ -6,7 +6,6 @@ from time import sleep -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import metrics from opentelemetry.sdk.metrics.export import ( MetricExportResult, @@ -14,6 +13,7 @@ MetricsData, PeriodicExportingMetricReader, ) +from azure.monitor.opentelemetry import configure_azure_monitor class PrintMetricExporter(MetricExporter): @@ -27,7 +27,7 @@ def export(self, metrics_data: MetricsData, **kwargs) -> MetricExportResult: # def shutdown(self, timeout_millis: float = 30000, **kwargs) -> None: # type: ignore[override] return None - def force_flush(self, timeout_millis: float = 30000, **kwargs) -> bool: # type: ignore[override] + def force_flush(self, timeout_millis: float = 30000, **kwargs) -> bool: # type: ignore[override] # pylint: disable=unused-argument return True diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/views.py b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/views.py index 1affc1dcd684..1411d5a6a389 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/views.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/metrics/views.py @@ -4,10 +4,10 @@ # license information. # -------------------------------------------------------------------------- -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import metrics from opentelemetry.sdk.metrics import Counter from opentelemetry.sdk.metrics.view import View +from azure.monitor.opentelemetry import configure_azure_monitor # Create a view matching the counter instrument `my.counter` # and configure the new name `my.counter.total` for the result metrics stream diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_ai_inference.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_ai_inference.py index 90e2caec8426..52132aa54775 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_ai_inference.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_ai_inference.py @@ -4,15 +4,15 @@ # license information. # -------------------------------------------------------------------------- -from os import environ import os +import sys +from opentelemetry import trace from azure.ai.inference import ChatCompletionsClient -from azure.ai.inference.models import SystemMessage, UserMessage, CompletionsFinishReason +from azure.ai.inference.models import UserMessage from azure.core.credentials import AzureKeyCredential from azure.monitor.opentelemetry import configure_azure_monitor -from opentelemetry import trace # Set up exporting to Azure Monitor configure_azure_monitor() @@ -25,12 +25,12 @@ except KeyError: print("Missing environment variable 'AZURE_AI_CHAT_ENDPOINT' or 'AZURE_AI_CHAT_KEY'") print("Set them before running this sample.") - exit() + sys.exit() is_content_tracing_enabled = os.environ["AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED"] if not is_content_tracing_enabled: print( - f"Content tracing is disabled. Set 'AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED' to 'true' to record prompts and completions." + "Content tracing is disabled. Set 'AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED' to 'true' to record prompts and completions." # pylint: disable=line-too-long ) tracer = trace.get_tracer(__name__) diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_blob_storage.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_blob_storage.py index 5a31c6e49dfc..6a4661f1ea97 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_blob_storage.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/azure_blob_storage.py @@ -6,15 +6,15 @@ from os import environ -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace +from azure.monitor.opentelemetry import configure_azure_monitor +from azure.storage.blob import BlobServiceClient # Set up exporting to Azure Monitor configure_azure_monitor() # Example with Storage SDKs -from azure.storage.blob import BlobServiceClient tracer = trace.get_tracer(__name__) with tracer.start_as_current_span(name="MyApplication"): diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/admin.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/admin.py index e1ceac9b70c3..43d12812791b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/admin.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/admin.py @@ -4,6 +4,6 @@ # license information. # -------------------------------------------------------------------------- -from django.contrib import admin +from django.contrib import admin # pylint: disable=unused-import # Register your models here. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/models.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/models.py index 95f07cd2eeed..0330dba206bf 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/models.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/models.py @@ -4,6 +4,6 @@ # license information. # -------------------------------------------------------------------------- -from django.db import models +from django.db import models # pylint: disable=unused-import # Create your models here. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/tests.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/tests.py index 81c546d8d6f1..ed3b43921895 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/tests.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/tests.py @@ -4,6 +4,6 @@ # license information. # -------------------------------------------------------------------------- -from django.test import TestCase +from django.test import TestCase # pylint: disable=unused-import # Create your tests here. diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/views.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/views.py index 37961b951f3c..c37364533eb4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/views.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/example/views.py @@ -8,10 +8,10 @@ # Requests sent to the django application will be automatically captured -def index(request): +def index(_request): return HttpResponse("Hello, world.") # Exceptions that are raised within the request are automatically captured -def exception(request): - raise Exception("Exception was raised.") +def exception(_request): + raise Exception("Exception was raised.") # pylint: disable=broad-exception-raised diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/manage.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/manage.py index cb16334e3e45..760554d80513 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/manage.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/manage.py @@ -17,7 +17,8 @@ def main(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") # Configure Azure monitor collection telemetry pipeline - # configure_azure_monitor should only be called once in either asgi.py, wsgi.py, or manage.py, depending on startup method. + # configure_azure_monitor should only be called once in either asgi.py, wsgi.py, or manage.py, + # depending on startup method. # If using manage.py, please remove configure_azure_monitor from asgi.py and wsgi.py configure_azure_monitor() diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/asgi.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/asgi.py index 0f2410b4887c..13ed4dfa1426 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/asgi.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/asgi.py @@ -16,14 +16,15 @@ import os -from azure.monitor.opentelemetry import configure_azure_monitor from django.core.asgi import get_asgi_application +from azure.monitor.opentelemetry import configure_azure_monitor os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") # Configure Azure monitor collection telemetry pipeline -# configure_azure_monitor should only be called once in etiher asgi.py, wsgi.py, or manage.py, depending on startup method. +# configure_azure_monitor should only be called once in etiher asgi.py, wsgi.py, or manage.py, +# depending on startup method. # If using asgi, please remove configure_azure_monitor from wsgi.py and manage.py configure_azure_monitor() diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/wsgi.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/wsgi.py index c4ad859f4931..57d4d43649ad 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/wsgi.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/django/sample/sample/wsgi.py @@ -15,14 +15,15 @@ import os -from azure.monitor.opentelemetry import configure_azure_monitor from django.core.wsgi import get_wsgi_application +from azure.monitor.opentelemetry import configure_azure_monitor os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") # Configure Azure monitor collection telemetry pipeline -# configure_azure_monitor should only be called once in either asgi.py, wsgi.py, or manage.py, depending on startup method. +# configure_azure_monitor should only be called once in either asgi.py, wsgi.py, or manage.py, +# depending on startup method. # If using wsgi, please remove configure_azure_monitor from asgi.py and manage.py configure_azure_monitor() diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/filter_spans.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/filter_spans.py index eb6aecccb076..bc921a6d61cd 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/filter_spans.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/filter_spans.py @@ -4,13 +4,14 @@ # license information. # -------------------------------------------------------------------------- -import requests # type: ignore[import-untyped] -from azure.monitor.opentelemetry import configure_azure_monitor +import requests # type: ignore[import-untyped] # pylint: disable=networking-import-outside-azure-core-transport from opentelemetry.sdk.trace import SpanProcessor from opentelemetry.trace import get_tracer, SpanContext, SpanKind, TraceFlags +from azure.monitor.opentelemetry import configure_azure_monitor # Define a custom processor to filter your spans +# pylint: disable=protected-access class SpanFilteringProcessor(SpanProcessor): # Prevents exporting spans that are of kind INTERNAL def on_start(self, span, parent_context): # type: ignore diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py index 2abd4c3cd86a..b02787222e3e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py @@ -24,7 +24,7 @@ async def test(): # Exceptions that are raised within the request are automatically captured @app.get("/exception") async def exception(): - raise Exception("Hit an exception") + raise Exception("Hit an exception") # pylint: disable=broad-exception-raised # Set the OTEL_PYTHON_EXCLUDED_URLS environment variable to "http://127.0.0.1:8000/exclude" diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_flask.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_flask.py index 4729866e540e..e17cc2218149 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_flask.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_flask.py @@ -10,7 +10,7 @@ configure_azure_monitor() # Import Flask after running configure_azure_monitor() -import flask +import flask # pylint: disable=wrong-import-position, wrong-import-order app = flask.Flask(__name__) @@ -24,7 +24,7 @@ def test(): # Exceptions that are raised within the request are automatically captured @app.route("/exception") def exception(): - raise Exception("Hit an exception") + raise Exception("Hit an exception") # pylint: disable=broad-exception-raised # Requests sent to this endpoint will not be tracked due to diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_requests.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_requests.py index 66f8b1b09eeb..7c6db5b37956 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_requests.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_requests.py @@ -6,9 +6,9 @@ import logging -import requests # type: ignore[import-untyped] -from azure.monitor.opentelemetry import configure_azure_monitor +import requests # type: ignore[import-untyped] # pylint: disable=networking-import-outside-azure-core-transport from opentelemetry import trace +from azure.monitor.opentelemetry import configure_azure_monitor logger = logging.getLogger(__name__) @@ -24,7 +24,7 @@ # This request will not be tracked due to the excluded_urls configuration response = requests.get("http://example.com", timeout=5) logger.warning("Request sent") - except Exception as ex: + except Exception as ex: # pylint: disable=broad-exception-caught # If an exception occurs, this can be manually recorded on the parent span span.set_attribute("status", "exception") span.record_exception(ex) diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib.py index 7b561922bfc6..cb5eda094dca 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib.py @@ -7,8 +7,8 @@ import logging from urllib import request -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace +from azure.monitor.opentelemetry import configure_azure_monitor logger = logging.getLogger(__name__) @@ -20,9 +20,9 @@ try: # Requests made using the urllib library will be automatically captured req = request.Request("https://www.example.org/", method="GET") - r = request.urlopen(req) - logger.warning("Request sent") - except Exception as ex: + with request.urlopen(req) as _: + logger.warning("Request sent") + except Exception as ex: # pylint: disable=broad-exception-caught # If an exception occurs, this can be manually recorded on the parent span span.set_attribute("status", "exception") span.record_exception(ex) diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py index f14e57c08dbb..1a99d6cd30d2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py @@ -7,8 +7,8 @@ import logging import urllib3 -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace +from azure.monitor.opentelemetry import configure_azure_monitor logger = logging.getLogger(__name__) @@ -23,7 +23,7 @@ # Requests made using the urllib3 library will be automatically captured response = http.request("GET", "https://www.example.org/") logger.warning("Request sent") - except Exception as ex: + except Exception as ex: # pylint: disable=broad-exception-caught # If an exception occurs, this can be manually recorded on the parent span span.set_attribute("status", "exception") span.record_exception(ex) diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py index 19c9433f24d6..8a12f80991da 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/manually_instrumented.py @@ -4,9 +4,9 @@ # license information. # -------------------------------------------------------------------------- -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor from sqlalchemy import create_engine, text +from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor() diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/modify_spans.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/modify_spans.py index 9a053aa22ca6..19a91b7dd31c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/modify_spans.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/modify_spans.py @@ -4,11 +4,12 @@ # license information. # -------------------------------------------------------------------------- -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace from opentelemetry.sdk.trace import SpanProcessor +from azure.monitor.opentelemetry import configure_azure_monitor +# pylint: disable=protected-access # Define a custom processor to modify your spans class SpanEnrichingProcessor(SpanProcessor): def on_end(self, span): diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling.py index 23d996e28754..2107b14ef345 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling.py @@ -4,8 +4,8 @@ # license information. # -------------------------------------------------------------------------- -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace +from azure.monitor.opentelemetry import configure_azure_monitor # Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.1 # Sampling ratio of between 0 and 1 inclusive diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py index 55370292dece..61066892bf19 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/sampling_configurations.py @@ -4,8 +4,8 @@ # license information. # -------------------------------------------------------------------------- -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace +from azure.monitor.opentelemetry import configure_azure_monitor # Using always_on sampler # Set the OTEL_TRACES_SAMPLER environment variable to "always_on" @@ -17,7 +17,8 @@ # Using trace_id_ratio sampler # Set the OTEL_TRACES_SAMPLER environment variable to "trace_id_ratio" -# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.1; it must be a number between 0 and 1 or it defaults to 1.0. +# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.1; it must be a number between 0 and 1 +# or it defaults to 1.0. # A sampling rate of 0.1 means approximately 10% of your traces are sent. # Using parentbased_always_on sampler @@ -30,42 +31,46 @@ # Using parentbased_trace_id_ratio sampler # Set the OTEL_TRACES_SAMPLER environment variable to "parentbased_trace_id_ratio" -# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.45; it must be a number between 0 and 1 or it defaults to 1.0. +# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.45; it must be a number between 0 and 1 +# or it defaults to 1.0. # A sampling rate of 0.45 means approximately 45% of your traces are sent. # Using rate limited sampler (this is the default sampler) # Set the OTEL_TRACES_SAMPLER environment variable to "microsoft.rate_limited" -# Set the OTEL_TRACES_SAMPLER_ARG environment variable to the desired rate limit (e.g., 0.5 means one trace every two seconds, while 5.0 means five traces per second) -# You can also configure the rate limited sampler by passing the `traces_per_second` argument to `configure_azure_monitor`. +# Set the OTEL_TRACES_SAMPLER_ARG environment variable to the desired rate limit (e.g., 0.5 means +# one trace every two seconds, while 5.0 means five traces per second) +# You can also configure the rate limited sampler by passing the `traces_per_second` argument to +# `configure_azure_monitor`. -""" - configure_azure_monitor ( - traces_per_second: 0.5, - ) -""" +# Example: configure rate-limited sampler directly via code +# configure_azure_monitor( +# traces_per_second=0.5, +# ) # Using fixed percentage sampler # Set the OTEL_TRACES_SAMPLER environment variable to "microsoft.fixed_percentage" -# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.2; it must be a number between 0 and 1 or it defaults to 1.0. -# When configuring sampling via `configure_azure_monitor`, the default sampler is rate limited. To use the classic Application Insights sampler instead, set `sampling_ratio` to 1.0. # pylint: disable=line-too-long +# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.2; it must be a number between 0 and 1 or +# it defaults to 1.0. +# When configuring sampling via `configure_azure_monitor`, the default sampler is rate limited. To use the classic Application Insights # pylint: disable=line-too-long +# sampler instead, set `sampling_ratio` to 1.0. # pylint: disable=line-too-long -""" - configure_azure_monitor ( - sampling_ratio: 1.0, - ) -""" +# Example: configure fixed-percentage sampler via code +# configure_azure_monitor( +# sampling_ratio=1.0, +# traces_per_second=0.0, +# ) # Using trace_based_sampling configuration # cspell: ignore unsampled # Determines whether the logger should drop log records associated with unsampled traces. -# Passing the enable_trace_based_sampling_for_logs=True argument to configure_azure_monitor ensures that log records associated with unsampled traces are dropped by the logger. +# Passing the enable_trace_based_sampling_for_logs=True argument to configure_azure_monitor ensures that log records associated with +# unsampled traces are dropped by the logger. # A log record is considered associated with an unsampled trace if it has a valid `SpanId` and its `TraceFlags` indicate that the trace is unsampled. # The value of this config is False by default. -""" - configure_azure_monitor ( - enable_trace_based_sampling_for_logs: True, - ) -""" +# Example: enable trace-based sampling for logs +# configure_azure_monitor( +# enable_trace_based_sampling_for_logs=True, +# ) configure_azure_monitor() diff --git a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/simple.py b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/simple.py index 5bfdf21c374e..f12ca487da90 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/simple.py +++ b/sdk/monitor/azure-monitor-opentelemetry/samples/tracing/simple.py @@ -4,8 +4,8 @@ # license information. # -------------------------------------------------------------------------- -from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace +from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor() diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py b/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py index 97416438ecf1..f1eec2a8c563 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py @@ -8,7 +8,6 @@ from unittest import TestCase from unittest.mock import patch -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan from azure.monitor.opentelemetry._autoinstrumentation.configurator import ( AzureMonitorConfigurator, ) @@ -18,6 +17,7 @@ ) +# pylint: disable=unused-argument @patch.dict("os.environ", {}, clear=True) class TestConfigurator(TestCase): @patch("azure.monitor.opentelemetry._autoinstrumentation.configurator.super") diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py b/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py index 65babb43144a..6f84a08ee5ae 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py @@ -16,6 +16,7 @@ from azure.monitor.opentelemetry._diagnostics.diagnostic_logging import _ATTACH_FAILURE_DISTRO, _ATTACH_SUCCESS_DISTRO +# pylint: disable=unused-argument class TestDistro(TestCase): @patch.dict("os.environ", {}, clear=True) @patch("azure.monitor.opentelemetry._autoinstrumentation.distro._is_attach_enabled", return_value=True) diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/diagnostics/test_diagnostic_logging.py b/sdk/monitor/azure-monitor-opentelemetry/tests/diagnostics/test_diagnostic_logging.py index 7a0e02407dbd..a0e7088339da 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/diagnostics/test_diagnostic_logging.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/diagnostics/test_diagnostic_logging.py @@ -4,7 +4,6 @@ # license information. # -------------------------------------------------------------------------- -import logging import os from importlib import reload from json import loads @@ -25,13 +24,13 @@ def clear_file(file_path): - with open(file_path, "w") as f: + with open(file_path, "w", encoding="utf-8") as f: f.seek(0) f.truncate() def check_file_for_messages(file_path, level, messages): - with open(file_path, "r") as f: + with open(file_path, "r", encoding="utf-8") as f: f.seek(0) for message, message_id in messages: json = loads(f.readline()) @@ -51,7 +50,7 @@ def check_file_for_messages(file_path, level, messages): def check_file_is_empty(file_path): - with open(file_path, "r") as f: + with open(file_path, "r", encoding="utf-8") as f: f.seek(0) assert not f.read() @@ -205,7 +204,9 @@ def test_initialize_makedirs_file_exists_error_handled(self, temp_file_path): # Mock makedirs to raise FileExistsError (this should be handled gracefully) with patch("azure.monitor.opentelemetry._diagnostics.diagnostic_logging.makedirs") as mock_makedirs, patch( "azure.monitor.opentelemetry._diagnostics.diagnostic_logging.exists", return_value=False - ), patch("azure.monitor.opentelemetry._diagnostics.diagnostic_logging._logger") as mock_logger: + ), patch( + "azure.monitor.opentelemetry._diagnostics.diagnostic_logging._logger" + ) as mock_logger: # pylint: disable=unused-variable mock_makedirs.side_effect = FileExistsError("Directory already exists") # Attempt to log, which will trigger initialization diagnostic_logger.AzureDiagnosticLogging.info(MESSAGE1, "4200") diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/diagnostics/test_status_logger.py b/sdk/monitor/azure-monitor-opentelemetry/tests/diagnostics/test_status_logger.py index 9187f78c12dc..273bb4d35c37 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/diagnostics/test_status_logger.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/diagnostics/test_status_logger.py @@ -63,7 +63,7 @@ def set_up(file_path, is_diagnostics_enabled=True): def check_file_for_messages(agent_initialized_successfully, file_path, reason=None, sdk_present=None): - with open(file_path, "r") as f: + with open(file_path, "r", encoding="utf-8") as f: f.seek(0) json = loads(f.readline()) assert json["AgentInitializedSuccessfully"] == agent_initialized_successfully @@ -85,7 +85,7 @@ def check_file_for_messages(agent_initialized_successfully, file_path, reason=No def check_file_is_empty(file_path): - with open(file_path, "r") as f: + with open(file_path, "r", encoding="utf-8") as f: f.seek(0) assert not f.read() diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/instrumentation/test_psycopg2.py b/sdk/monitor/azure-monitor-opentelemetry/tests/instrumentation/test_psycopg2.py index 96fada6fd49f..4401ce48729e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/instrumentation/test_psycopg2.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/instrumentation/test_psycopg2.py @@ -5,9 +5,9 @@ # -------------------------------------------------------------------------- import os -import pytest import sys import unittest +import pytest # Skip for Python v3.13 until https://github.com/psycopg/psycopg2/pull/1729 is resolved # Skip for Python v3.8 on windows due to https://github.com/psycopg/psycopg/issues/936 diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/test_configure.py b/sdk/monitor/azure-monitor-opentelemetry/tests/test_configure.py index 1db4b9adc5bd..7adfbeb5b33f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/test_configure.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/test_configure.py @@ -14,10 +14,8 @@ import unittest from unittest.mock import Mock, call, patch -from opentelemetry.sdk._logs import LoggingHandler from opentelemetry.sdk.resources import Resource -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan from azure.monitor.opentelemetry._configure import ( _send_attach_warning, _setup_instrumentations, @@ -33,6 +31,7 @@ TEST_RESOURCE = Resource({"foo": "bar"}) +# pylint: disable=too-many-public-methods class TestConfigure(unittest.TestCase): @patch( "azure.monitor.opentelemetry._configure._send_attach_warning", diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py b/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py index e4bdc34f5a5c..81caeeda6faf 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_configurations.py @@ -26,6 +26,12 @@ OTEL_PYTHON_DISABLED_INSTRUMENTATIONS, ) from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ALWAYS_ON, ParentBased, TraceIdRatioBased +from opentelemetry.environment_variables import ( + OTEL_LOGS_EXPORTER, + OTEL_METRICS_EXPORTER, + OTEL_TRACES_EXPORTER, +) +from opentelemetry.sdk.resources import Resource from azure.monitor.opentelemetry._utils.configurations import ( _get_configurations, _get_sampler_from_name, @@ -41,16 +47,8 @@ PARENT_BASED_ALWAYS_OFF_SAMPLER, PARENT_BASED_ALWAYS_ON_SAMPLER, PARENT_BASED_TRACE_ID_RATIO_SAMPLER, - SAMPLING_ARG, METRIC_READERS_ARG, ) -from opentelemetry.environment_variables import ( - OTEL_LOGS_EXPORTER, - OTEL_METRICS_EXPORTER, - OTEL_TRACES_EXPORTER, -) -from opentelemetry.sdk.environment_variables import OTEL_EXPERIMENTAL_RESOURCE_DETECTORS -from opentelemetry.sdk.resources import Resource from azure.monitor.opentelemetry._version import VERSION @@ -62,6 +60,7 @@ ) +# pylint: disable=too-many-public-methods, unused-argument class TestConfigurations(TestCase): @patch.dict("os.environ", {}, clear=True) @patch( @@ -397,7 +396,6 @@ def test_get_configurations_logging_format_env_var_invalid_format(self, mock_log clear=True, ) def test_get_configurations_logging_format_param_overrides_env_var(self): - from logging import Formatter custom_formatter = Formatter("%(levelname)s: %(message)s") configurations = _get_configurations(logging_formatter=custom_formatter) @@ -716,24 +714,6 @@ def test_get_configurations_env_vars_trace_id_ratio_non_numeric_value(self, reso self.assertEqual(configurations["sampling_arg"], 1.0) self.assertEqual(configurations["sampler_type"], "trace_id_ratio") - @patch.dict( - "os.environ", - { - OTEL_PYTHON_DISABLED_INSTRUMENTATIONS: "flask,requests,fastapi,azure_sdk", - OTEL_TRACES_SAMPLER: TRACE_ID_RATIO_SAMPLER, - OTEL_TRACES_SAMPLER_ARG: "sampler", - }, - clear=True, - ) - @patch("opentelemetry.sdk.resources.Resource.create", return_value=TEST_DEFAULT_RESOURCE) - def test_get_configurations_env_vars_trace_id_ratio_non_numeric_value(self, resource_create_mock): - configurations = _get_configurations() - - self.assertTrue("connection_string" not in configurations) - self.assertEqual(configurations["resource"].attributes, TEST_DEFAULT_RESOURCE.attributes) - self.assertEqual(configurations["sampling_arg"], 1.0) - self.assertEqual(configurations["sampler_type"], "trace_id_ratio") - @patch.dict( "os.environ", { diff --git a/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_utils.py index 55283ace2690..8876f368be52 100644 --- a/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry/tests/utils/test_utils.py @@ -10,11 +10,10 @@ from unittest.mock import patch from azure.monitor.opentelemetry import _utils -from azure.monitor.opentelemetry.exporter._constants import _AKS_ARM_NAMESPACE_ID TEST_VALUE = "TEST_VALUE" TEST_IKEY = "1234abcd-ab12-34cd-ab12-a23456abcdef" -TEST_CONN_STR = f"InstrumentationKey={TEST_IKEY};IngestionEndpoint=https://centralus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://centralus.livediagnostics.monitor.azure.com/" +TEST_CONN_STR = f"InstrumentationKey={TEST_IKEY};IngestionEndpoint=https://centralus-2.in.applicationinsights.azure.com/;LiveEndpoint=https://centralus.livediagnostics.monitor.azure.com/" # pylint: disable=line-too-long def clear_env_var(env_var): @@ -22,6 +21,7 @@ def clear_env_var(env_var): del environ[env_var] +# pylint: disable=unused-argument class TestUtils(TestCase): @patch.dict( "os.environ",