diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index 35327240d4ab..af43d7ff1660 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -6,6 +6,10 @@ ### Breaking Changes +- Serialize complex objects provided as log or event bodies to JSON and + fall back to string representation if they are not serializable. + ([37694](https://github.com/Azure/azure-sdk-for-python/pull/37694)) + ### Bugs Fixed ### Other Changes @@ -486,7 +490,7 @@ ([#78](https://github.com/microsoft/opentelemetry-azure-monitor-python/pull/78)) - Handle status 439 - Too Many Requests over extended time ([#80](https://github.com/microsoft/opentelemetry-azure-monitor-python/pull/80)) -- Fix breaking changes from OT release 0.7b.0 +- Fix breaking changes from OT release 0.7b.0 ([#86](https://github.com/microsoft/opentelemetry-azure-monitor-python/pull/86)) ## 0.2b.0 (2020-03-31) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/__init__.py index 69e3be50dac4..8db66d3d0f0f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/__init__.py index 0c36c2076ba0..d55ccad1f573 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_connection_string_parser.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_connection_string_parser.py index d11fd408562e..767ca8e0df66 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_connection_string_parser.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_connection_string_parser.py @@ -10,13 +10,7 @@ # Validate UUID format # Specs taken from https://tools.ietf.org/html/rfc4122 -uuid_regex_pattern = re.compile( - "^[0-9a-f]{8}-" - "[0-9a-f]{4}-" - "[0-9a-f]{4}-" - "[0-9a-f]{4}-" - "[0-9a-f]{12}$" -) +uuid_regex_pattern = re.compile("^[0-9a-f]{8}-" "[0-9a-f]{4}-" + "[0-9a-f]{4}-" "[0-9a-f]{4}-" "[0-9a-f]{12}$") class ConnectionStringParser: @@ -27,10 +21,7 @@ class ConnectionStringParser: :rtype: None """ - def __init__( - self, - connection_string: typing.Optional[str] = None - ) -> None: + def __init__(self, connection_string: typing.Optional[str] = None) -> None: self.instrumentation_key = None self.endpoint = "" self.live_endpoint = "" @@ -42,9 +33,7 @@ def _initialize(self) -> None: # connection string and ikey code_cs = self._parse_connection_string(self._connection_string) code_ikey = self.instrumentation_key - env_cs = self._parse_connection_string( - os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING") - ) + env_cs = self._parse_connection_string(os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING")) env_ikey = os.getenv("APPINSIGHTS_INSTRUMENTATIONKEY") # The priority of which value takes on the instrumentation key is: @@ -53,27 +42,19 @@ def _initialize(self) -> None: # 3. Key from connection string in environment variable # 4. Key from instrumentation key in environment variable self.instrumentation_key = ( - code_cs.get(INSTRUMENTATION_KEY) # type: ignore - or code_ikey - or env_cs.get(INSTRUMENTATION_KEY) - or env_ikey + code_cs.get(INSTRUMENTATION_KEY) or code_ikey or env_cs.get(INSTRUMENTATION_KEY) or env_ikey # type: ignore ) # The priority of the endpoints is as follows: # 1. The endpoint explicitly passed in connection string # 2. The endpoint from the connection string in environment variable # 3. The default breeze endpoint self.endpoint = ( - code_cs.get(INGESTION_ENDPOINT) - or env_cs.get(INGESTION_ENDPOINT) - or "https://dc.services.visualstudio.com" + code_cs.get(INGESTION_ENDPOINT) or env_cs.get(INGESTION_ENDPOINT) or "https://dc.services.visualstudio.com" ) self.live_endpoint = ( - code_cs.get(LIVE_ENDPOINT) - or env_cs.get(LIVE_ENDPOINT) - or "https://rt.services.visualstudio.com" + code_cs.get(LIVE_ENDPOINT) or env_cs.get(LIVE_ENDPOINT) or "https://rt.services.visualstudio.com" ) - def _validate_instrumentation_key(self) -> None: """Validates the instrumentation key used for Azure Monitor. @@ -84,8 +65,7 @@ def _validate_instrumentation_key(self) -> None: raise ValueError("Instrumentation key cannot be none or empty.") match = uuid_regex_pattern.match(self.instrumentation_key) if not match: - raise ValueError( - "Invalid instrumentation key. It should be a valid UUID.") + raise ValueError("Invalid instrumentation key. It should be a valid UUID.") def _parse_connection_string(self, connection_string) -> typing.Dict: if connection_string is None: @@ -117,17 +97,13 @@ def _parse_connection_string(self, connection_string) -> typing.Dict: # Construct the endpoints if not passed in explicitly if result.get(INGESTION_ENDPOINT) is None: if endpoint_suffix: - result[INGESTION_ENDPOINT] = "https://{0}dc.{1}".format( - location_prefix, endpoint_suffix - ) + result[INGESTION_ENDPOINT] = "https://{0}dc.{1}".format(location_prefix, endpoint_suffix) else: # Default to None if cannot construct result[INGESTION_ENDPOINT] = None if result.get(LIVE_ENDPOINT) is None: if endpoint_suffix: - result[LIVE_ENDPOINT] = "https://{0}live.{1}".format( - location_prefix, endpoint_suffix - ) + result[LIVE_ENDPOINT] = "https://{0}live.{1}".format(location_prefix, endpoint_suffix) else: result[LIVE_ENDPOINT] = None diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_constants.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_constants.py index 1216c6731bd0..048b900da8ee 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_constants.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_constants.py @@ -7,8 +7,9 @@ # Environment variables _APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL = "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL" -_APPLICATIONINSIGHTS_OPENTELEMETRY_RESOURCE_METRIC_DISABLED = \ +_APPLICATIONINSIGHTS_OPENTELEMETRY_RESOURCE_METRIC_DISABLED = ( "APPLICATIONINSIGHTS_OPENTELEMETRY_RESOURCE_METRIC_DISABLED" +) _APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN = "APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN" # RPs @@ -22,9 +23,7 @@ # Network -_INVALID_STATUS_CODES = ( - 400, # Invalid Instrumentation Key/data -) +_INVALID_STATUS_CODES = (400,) # Invalid Instrumentation Key/data _REDIRECT_STATUS_CODES = ( 307, # Temporary redirect diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/__init__.py index 4973f7579f0b..6d010691a414 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/__init__.py @@ -7,9 +7,11 @@ # -------------------------------------------------------------------------- from ._azure_monitor_client import AzureMonitorClient -__all__ = ['AzureMonitorClient'] + +__all__ = ["AzureMonitorClient"] # `._patch.py` is used for handwritten extensions to the generated code # Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md from ._patch import patch_sdk + patch_sdk() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_azure_monitor_client.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_azure_monitor_client.py index d1ec12e2bc7f..6ea083bbd4c4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_azure_monitor_client.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_azure_monitor_client.py @@ -23,6 +23,7 @@ from azure.core.rest import HttpRequest, HttpResponse + class AzureMonitorClient(AzureMonitorClientOperationsMixin): """OpenTelemetry Exporter for Azure Monitor. @@ -37,7 +38,7 @@ def __init__( **kwargs # type: Any ): # type: (...) -> None - _base_url = '{Host}/v2.1' + _base_url = "{Host}/v2.1" self._config = AzureMonitorClientConfiguration(host=host, **kwargs) self._client = PipelineClient(base_url=_base_url, config=self._config, **kwargs) @@ -46,7 +47,6 @@ def __init__( self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - def _send_request( self, request, # type: HttpRequest @@ -72,7 +72,7 @@ def _send_request( request_copy = deepcopy(request) path_format_arguments = { - "Host": self._serialize.url("self._config.host", self._config.host, 'str', skip_quote=True), + "Host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_configuration.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_configuration.py index 24007e472e38..8fa05dbefe89 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_configuration.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_configuration.py @@ -17,6 +17,7 @@ VERSION = "unknown" + class AzureMonitorClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AzureMonitorClient. @@ -39,20 +40,19 @@ def __init__( raise ValueError("Parameter 'host' must not be None.") self.host = host - kwargs.setdefault('sdk_moniker', 'azuremonitorclient/{}'.format(VERSION)) + kwargs.setdefault("sdk_moniker", "azuremonitorclient/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_patch.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_patch.py index 74e48ecd07cf..17dbc073e01b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_patch.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_patch.py @@ -25,7 +25,8 @@ # # -------------------------------------------------------------------------- + # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_vendor.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_vendor.py index 9a223d15524c..0dafe0e287ff 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_vendor.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/_vendor.py @@ -7,6 +7,7 @@ from azure.core.pipeline.transport import HttpRequest + def _convert_request(request, files=None): data = request.content if not files else None request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/__init__.py index 4973f7579f0b..6d010691a414 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/__init__.py @@ -7,9 +7,11 @@ # -------------------------------------------------------------------------- from ._azure_monitor_client import AzureMonitorClient -__all__ = ['AzureMonitorClient'] + +__all__ = ["AzureMonitorClient"] # `._patch.py` is used for handwritten extensions to the generated code # Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md from ._patch import patch_sdk + patch_sdk() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_azure_monitor_client.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_azure_monitor_client.py index 3cf75b1a463f..e829f0d44fa6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_azure_monitor_client.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_azure_monitor_client.py @@ -18,6 +18,7 @@ from ._configuration import AzureMonitorClientConfiguration from .operations import AzureMonitorClientOperationsMixin + class AzureMonitorClient(AzureMonitorClientOperationsMixin): """OpenTelemetry Exporter for Azure Monitor. @@ -26,12 +27,8 @@ class AzureMonitorClient(AzureMonitorClientOperationsMixin): :type host: str """ - def __init__( - self, - host: str = "https://dc.services.visualstudio.com", - **kwargs: Any - ) -> None: - _base_url = '{Host}/v2.1' + def __init__(self, host: str = "https://dc.services.visualstudio.com", **kwargs: Any) -> None: + _base_url = "{Host}/v2.1" self._config = AzureMonitorClientConfiguration(host=host, **kwargs) self._client = AsyncPipelineClient(base_url=_base_url, config=self._config, **kwargs) @@ -40,12 +37,7 @@ def __init__( self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False - - def _send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def _send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -65,7 +57,7 @@ def _send_request( request_copy = deepcopy(request) path_format_arguments = { - "Host": self._serialize.url("self._config.host", self._config.host, 'str', skip_quote=True), + "Host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_configuration.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_configuration.py index 80bba32af67b..1bc76b30457b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_configuration.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_configuration.py @@ -13,6 +13,7 @@ VERSION = "unknown" + class AzureMonitorClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for AzureMonitorClient. @@ -24,29 +25,22 @@ class AzureMonitorClientConfiguration(Configuration): # pylint: disable=too-man :type host: str """ - def __init__( - self, - host: str = "https://dc.services.visualstudio.com", - **kwargs: Any - ) -> None: + def __init__(self, host: str = "https://dc.services.visualstudio.com", **kwargs: Any) -> None: super(AzureMonitorClientConfiguration, self).__init__(**kwargs) if host is None: raise ValueError("Parameter 'host' must not be None.") self.host = host - kwargs.setdefault('sdk_moniker', 'azuremonitorclient/{}'.format(VERSION)) + kwargs.setdefault("sdk_moniker", "azuremonitorclient/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_patch.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_patch.py index 74e48ecd07cf..17dbc073e01b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_patch.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/_patch.py @@ -25,7 +25,8 @@ # # -------------------------------------------------------------------------- + # This file is used for handwritten extensions to the generated code. Example: # https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md def patch_sdk(): - pass \ No newline at end of file + pass diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/operations/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/operations/__init__.py index 30cdb38f8dbb..a1b6ce78bd5c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/operations/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/operations/__init__.py @@ -9,5 +9,5 @@ from ._azure_monitor_client_operations import AzureMonitorClientOperationsMixin __all__ = [ - 'AzureMonitorClientOperationsMixin', + "AzureMonitorClientOperationsMixin", ] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/operations/_azure_monitor_client_operations.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/operations/_azure_monitor_client_operations.py index 20d36078ebb4..72c70dab39a3 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/operations/_azure_monitor_client_operations.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/aio/operations/_azure_monitor_client_operations.py @@ -8,7 +8,13 @@ # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, List, Optional, TypeVar -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest @@ -16,16 +22,14 @@ from ... import models as _models from ..._vendor import _convert_request from ...operations._azure_monitor_client_operations import build_track_request -T = TypeVar('T') + +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + class AzureMonitorClientOperationsMixin: - async def track( - self, - body: List["_models.TelemetryItem"], - **kwargs: Any - ) -> "_models.TrackResponse": + async def track(self, body: List["_models.TelemetryItem"], **kwargs: Any) -> "_models.TrackResponse": """Track telemetry events. This operation sends a sequence of telemetry events that will be monitored by Azure Monitor. @@ -37,38 +41,46 @@ async def track( :rtype: ~azure_monitor_client.models.TrackResponse :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TrackResponse"] + cls = kwargs.pop("cls", None) # type: ClsType["_models.TrackResponse"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, - 400: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), - 402: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), - 429: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), - 500: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), - 503: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), + 400: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), + 402: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), + 429: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), + 500: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), + 503: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {})) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + content_type = kwargs.pop("content_type", "application/json") # type: Optional[str] - _json = self._serialize.body(body, '[TelemetryItem]') + _json = self._serialize.body(body, "[TelemetryItem]") request = build_track_request( content_type=content_type, json=_json, - template_url=self.track.metadata['url'], + template_url=self.track.metadata["url"], ) request = _convert_request(request) path_format_arguments = { - "Host": self._serialize.url("self._config.host", self._config.host, 'str', skip_quote=True), + "Host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -77,15 +89,14 @@ async def track( raise HttpResponseError(response=response) if response.status_code == 200: - deserialized = self._deserialize('TrackResponse', pipeline_response) + deserialized = self._deserialize("TrackResponse", pipeline_response) if response.status_code == 206: - deserialized = self._deserialize('TrackResponse', pipeline_response) + deserialized = self._deserialize("TrackResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - track.metadata = {'url': "/track"} # type: ignore - + track.metadata = {"url": "/track"} # type: ignore diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/__init__.py index e7b3dc28e2e9..2f29230ef836 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/__init__.py @@ -50,24 +50,24 @@ ) __all__ = [ - 'AvailabilityData', - 'MessageData', - 'MetricDataPoint', - 'MetricsData', - 'MonitorBase', - 'MonitorDomain', - 'PageViewData', - 'PageViewPerfData', - 'RemoteDependencyData', - 'RequestData', - 'StackFrame', - 'TelemetryErrorDetails', - 'TelemetryEventData', - 'TelemetryExceptionData', - 'TelemetryExceptionDetails', - 'TelemetryItem', - 'TrackResponse', - 'ContextTagKeys', - 'DataPointType', - 'SeverityLevel', + "AvailabilityData", + "MessageData", + "MetricDataPoint", + "MetricsData", + "MonitorBase", + "MonitorDomain", + "PageViewData", + "PageViewPerfData", + "RemoteDependencyData", + "RequestData", + "StackFrame", + "TelemetryErrorDetails", + "TelemetryEventData", + "TelemetryExceptionData", + "TelemetryExceptionDetails", + "TelemetryItem", + "TrackResponse", + "ContextTagKeys", + "DataPointType", + "SeverityLevel", ] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_azure_monitor_client_enums.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_azure_monitor_client_enums.py index a847a2618513..cb26c587c65b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_azure_monitor_client_enums.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_azure_monitor_client_enums.py @@ -11,8 +11,7 @@ class ContextTagKeys(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The context tag keys. - """ + """The context tag keys.""" AI_APPLICATION_VER = "ai.application.ver" AI_DEVICE_ID = "ai.device.id" @@ -43,16 +42,16 @@ class ContextTagKeys(str, Enum, metaclass=CaseInsensitiveEnumMeta): AI_INTERNAL_AGENT_VERSION = "ai.internal.agentVersion" AI_INTERNAL_NODE_NAME = "ai.internal.nodeName" + class DataPointType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of the metric data measurement. - """ + """Type of the metric data measurement.""" MEASUREMENT = "Measurement" AGGREGATION = "Aggregation" + class SeverityLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Defines the level of severity for the event. - """ + """Defines the level of severity for the event.""" VERBOSE = "Verbose" INFORMATION = "Information" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_models.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_models.py index 66784de06252..ceaf61192c50 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_models.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_models.py @@ -23,18 +23,15 @@ class MonitorDomain(msrest.serialization.Model): """ _validation = { - 'version': {'required': True}, + "version": {"required": True}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -43,8 +40,8 @@ def __init__( :paramtype version: int """ super(MonitorDomain, self).__init__(**kwargs) - self.additional_properties = kwargs.get('additional_properties', None) - self.version = kwargs.get('version', 2) + self.additional_properties = kwargs.get("additional_properties", None) + self.version = kwargs.get("version", 2) class AvailabilityData(MonitorDomain): @@ -77,32 +74,29 @@ class AvailabilityData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'required': True, 'max_length': 512, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'duration': {'required': True}, - 'success': {'required': True}, - 'run_location': {'max_length': 1024, 'min_length': 0}, - 'message': {'max_length': 8192, 'min_length': 0}, + "version": {"required": True}, + "id": {"required": True, "max_length": 512, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "duration": {"required": True}, + "success": {"required": True}, + "run_location": {"max_length": 1024, "min_length": 0}, + "message": {"max_length": 8192, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'success': {'key': 'success', 'type': 'bool'}, - 'run_location': {'key': 'runLocation', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "success": {"key": "success", "type": "bool"}, + "run_location": {"key": "runLocation", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -129,14 +123,14 @@ def __init__( :paramtype measurements: dict[str, float] """ super(AvailabilityData, self).__init__(**kwargs) - self.id = kwargs['id'] - self.name = kwargs['name'] - self.duration = kwargs['duration'] - self.success = kwargs['success'] - self.run_location = kwargs.get('run_location', None) - self.message = kwargs.get('message', None) - self.properties = kwargs.get('properties', None) - self.measurements = kwargs.get('measurements', None) + self.id = kwargs["id"] + self.name = kwargs["name"] + self.duration = kwargs["duration"] + self.success = kwargs["success"] + self.run_location = kwargs.get("run_location", None) + self.message = kwargs.get("message", None) + self.properties = kwargs.get("properties", None) + self.measurements = kwargs.get("measurements", None) class MessageData(MonitorDomain): @@ -161,23 +155,20 @@ class MessageData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'message': {'required': True, 'max_length': 32768, 'min_length': 0}, + "version": {"required": True}, + "message": {"required": True, "max_length": 32768, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'message': {'key': 'message', 'type': 'str'}, - 'severity_level': {'key': 'severityLevel', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "message": {"key": "message", "type": "str"}, + "severity_level": {"key": "severityLevel", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -195,10 +186,10 @@ def __init__( :paramtype measurements: dict[str, float] """ super(MessageData, self).__init__(**kwargs) - self.message = kwargs['message'] - self.severity_level = kwargs.get('severity_level', None) - self.properties = kwargs.get('properties', None) - self.measurements = kwargs.get('measurements', None) + self.message = kwargs["message"] + self.severity_level = kwargs.get("severity_level", None) + self.properties = kwargs.get("properties", None) + self.measurements = kwargs.get("measurements", None) class MetricDataPoint(msrest.serialization.Model): @@ -228,26 +219,23 @@ class MetricDataPoint(msrest.serialization.Model): """ _validation = { - 'namespace': {'max_length': 256, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'value': {'required': True}, + "namespace": {"max_length": 256, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "value": {"required": True}, } _attribute_map = { - 'namespace': {'key': 'ns', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'data_point_type': {'key': 'kind', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, - 'count': {'key': 'count', 'type': 'int'}, - 'min': {'key': 'min', 'type': 'float'}, - 'max': {'key': 'max', 'type': 'float'}, - 'std_dev': {'key': 'stdDev', 'type': 'float'}, + "namespace": {"key": "ns", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "data_point_type": {"key": "kind", "type": "str"}, + "value": {"key": "value", "type": "float"}, + "count": {"key": "count", "type": "int"}, + "min": {"key": "min", "type": "float"}, + "max": {"key": "max", "type": "float"}, + "std_dev": {"key": "stdDev", "type": "float"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword namespace: Namespace of the metric. :paramtype namespace: str @@ -270,14 +258,14 @@ def __init__( :paramtype std_dev: float """ super(MetricDataPoint, self).__init__(**kwargs) - self.namespace = kwargs.get('namespace', None) - self.name = kwargs['name'] - self.data_point_type = kwargs.get('data_point_type', None) - self.value = kwargs['value'] - self.count = kwargs.get('count', None) - self.min = kwargs.get('min', None) - self.max = kwargs.get('max', None) - self.std_dev = kwargs.get('std_dev', None) + self.namespace = kwargs.get("namespace", None) + self.name = kwargs["name"] + self.data_point_type = kwargs.get("data_point_type", None) + self.value = kwargs["value"] + self.count = kwargs.get("count", None) + self.min = kwargs.get("min", None) + self.max = kwargs.get("max", None) + self.std_dev = kwargs.get("std_dev", None) class MetricsData(MonitorDomain): @@ -299,21 +287,18 @@ class MetricsData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'metrics': {'required': True}, + "version": {"required": True}, + "metrics": {"required": True}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'metrics': {'key': 'metrics', 'type': '[MetricDataPoint]'}, - 'properties': {'key': 'properties', 'type': '{str}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "metrics": {"key": "metrics", "type": "[MetricDataPoint]"}, + "properties": {"key": "properties", "type": "{str}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -328,8 +313,8 @@ def __init__( :paramtype properties: dict[str, str] """ super(MetricsData, self).__init__(**kwargs) - self.metrics = kwargs['metrics'] - self.properties = kwargs.get('properties', None) + self.metrics = kwargs["metrics"] + self.properties = kwargs.get("properties", None) class MonitorBase(msrest.serialization.Model): @@ -343,14 +328,11 @@ class MonitorBase(msrest.serialization.Model): """ _attribute_map = { - 'base_type': {'key': 'baseType', 'type': 'str'}, - 'base_data': {'key': 'baseData', 'type': 'MonitorDomain'}, + "base_type": {"key": "baseType", "type": "str"}, + "base_data": {"key": "baseData", "type": "MonitorDomain"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword base_type: Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. @@ -359,8 +341,8 @@ def __init__( :paramtype base_data: ~azure_monitor_client.models.MonitorDomain """ super(MonitorBase, self).__init__(**kwargs) - self.base_type = kwargs.get('base_type', None) - self.base_data = kwargs.get('base_data', None) + self.base_type = kwargs.get("base_type", None) + self.base_data = kwargs.get("base_data", None) class PageViewData(MonitorDomain): @@ -395,29 +377,26 @@ class PageViewData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'required': True, 'max_length': 512, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'url': {'max_length': 2048, 'min_length': 0}, - 'referred_uri': {'max_length': 2048, 'min_length': 0}, + "version": {"required": True}, + "id": {"required": True, "max_length": 512, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "url": {"max_length": 2048, "min_length": 0}, + "referred_uri": {"max_length": 2048, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'referred_uri': {'key': 'referredUri', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "url": {"key": "url", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "referred_uri": {"key": "referredUri", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -445,13 +424,13 @@ def __init__( :paramtype measurements: dict[str, float] """ super(PageViewData, self).__init__(**kwargs) - self.id = kwargs['id'] - self.name = kwargs['name'] - self.url = kwargs.get('url', None) - self.duration = kwargs.get('duration', None) - self.referred_uri = kwargs.get('referred_uri', None) - self.properties = kwargs.get('properties', None) - self.measurements = kwargs.get('measurements', None) + self.id = kwargs["id"] + self.name = kwargs["name"] + self.url = kwargs.get("url", None) + self.duration = kwargs.get("duration", None) + self.referred_uri = kwargs.get("referred_uri", None) + self.properties = kwargs.get("properties", None) + self.measurements = kwargs.get("measurements", None) class PageViewPerfData(MonitorDomain): @@ -497,32 +476,29 @@ class PageViewPerfData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'required': True, 'max_length': 512, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'url': {'max_length': 2048, 'min_length': 0}, + "version": {"required": True}, + "id": {"required": True, "max_length": 512, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "url": {"max_length": 2048, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'perf_total': {'key': 'perfTotal', 'type': 'str'}, - 'network_connect': {'key': 'networkConnect', 'type': 'str'}, - 'sent_request': {'key': 'sentRequest', 'type': 'str'}, - 'received_response': {'key': 'receivedResponse', 'type': 'str'}, - 'dom_processing': {'key': 'domProcessing', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "url": {"key": "url", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "perf_total": {"key": "perfTotal", "type": "str"}, + "network_connect": {"key": "networkConnect", "type": "str"}, + "sent_request": {"key": "sentRequest", "type": "str"}, + "received_response": {"key": "receivedResponse", "type": "str"}, + "dom_processing": {"key": "domProcessing", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -562,17 +538,17 @@ def __init__( :paramtype measurements: dict[str, float] """ super(PageViewPerfData, self).__init__(**kwargs) - self.id = kwargs['id'] - self.name = kwargs['name'] - self.url = kwargs.get('url', None) - self.duration = kwargs.get('duration', None) - self.perf_total = kwargs.get('perf_total', None) - self.network_connect = kwargs.get('network_connect', None) - self.sent_request = kwargs.get('sent_request', None) - self.received_response = kwargs.get('received_response', None) - self.dom_processing = kwargs.get('dom_processing', None) - self.properties = kwargs.get('properties', None) - self.measurements = kwargs.get('measurements', None) + self.id = kwargs["id"] + self.name = kwargs["name"] + self.url = kwargs.get("url", None) + self.duration = kwargs.get("duration", None) + self.perf_total = kwargs.get("perf_total", None) + self.network_connect = kwargs.get("network_connect", None) + self.sent_request = kwargs.get("sent_request", None) + self.received_response = kwargs.get("received_response", None) + self.dom_processing = kwargs.get("dom_processing", None) + self.properties = kwargs.get("properties", None) + self.measurements = kwargs.get("measurements", None) class RemoteDependencyData(MonitorDomain): @@ -615,35 +591,32 @@ class RemoteDependencyData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'max_length': 512, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'result_code': {'max_length': 1024, 'min_length': 0}, - 'data': {'max_length': 8192, 'min_length': 0}, - 'type': {'max_length': 1024, 'min_length': 0}, - 'target': {'max_length': 1024, 'min_length': 0}, - 'duration': {'required': True}, + "version": {"required": True}, + "id": {"max_length": 512, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "result_code": {"max_length": 1024, "min_length": 0}, + "data": {"max_length": 8192, "min_length": 0}, + "type": {"max_length": 1024, "min_length": 0}, + "target": {"max_length": 1024, "min_length": 0}, + "duration": {"required": True}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'result_code': {'key': 'resultCode', 'type': 'str'}, - 'data': {'key': 'data', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'success': {'key': 'success', 'type': 'bool'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "result_code": {"key": "resultCode", "type": "str"}, + "data": {"key": "data", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "success": {"key": "success", "type": "bool"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -679,16 +652,16 @@ def __init__( :paramtype measurements: dict[str, float] """ super(RemoteDependencyData, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.name = kwargs['name'] - self.result_code = kwargs.get('result_code', None) - self.data = kwargs.get('data', None) - self.type = kwargs.get('type', None) - self.target = kwargs.get('target', None) - self.duration = kwargs['duration'] - self.success = kwargs.get('success', True) - self.properties = kwargs.get('properties', None) - self.measurements = kwargs.get('measurements', None) + self.id = kwargs.get("id", None) + self.name = kwargs["name"] + self.result_code = kwargs.get("result_code", None) + self.data = kwargs.get("data", None) + self.type = kwargs.get("type", None) + self.target = kwargs.get("target", None) + self.duration = kwargs["duration"] + self.success = kwargs.get("success", True) + self.properties = kwargs.get("properties", None) + self.measurements = kwargs.get("measurements", None) class RequestData(MonitorDomain): @@ -728,34 +701,31 @@ class RequestData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'required': True, 'max_length': 512, 'min_length': 0}, - 'name': {'max_length': 1024, 'min_length': 0}, - 'duration': {'required': True}, - 'success': {'required': True}, - 'response_code': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'source': {'max_length': 1024, 'min_length': 0}, - 'url': {'max_length': 2048, 'min_length': 0}, + "version": {"required": True}, + "id": {"required": True, "max_length": 512, "min_length": 0}, + "name": {"max_length": 1024, "min_length": 0}, + "duration": {"required": True}, + "success": {"required": True}, + "response_code": {"required": True, "max_length": 1024, "min_length": 0}, + "source": {"max_length": 1024, "min_length": 0}, + "url": {"max_length": 2048, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'success': {'key': 'success', 'type': 'bool'}, - 'response_code': {'key': 'responseCode', 'type': 'str'}, - 'source': {'key': 'source', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "success": {"key": "success", "type": "bool"}, + "response_code": {"key": "responseCode", "type": "str"}, + "source": {"key": "source", "type": "str"}, + "url": {"key": "url", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -788,15 +758,15 @@ def __init__( :paramtype measurements: dict[str, float] """ super(RequestData, self).__init__(**kwargs) - self.id = kwargs['id'] - self.name = kwargs.get('name', None) - self.duration = kwargs['duration'] - self.success = kwargs.get('success', True) - self.response_code = kwargs['response_code'] - self.source = kwargs.get('source', None) - self.url = kwargs.get('url', None) - self.properties = kwargs.get('properties', None) - self.measurements = kwargs.get('measurements', None) + self.id = kwargs["id"] + self.name = kwargs.get("name", None) + self.duration = kwargs["duration"] + self.success = kwargs.get("success", True) + self.response_code = kwargs["response_code"] + self.source = kwargs.get("source", None) + self.url = kwargs.get("url", None) + self.properties = kwargs.get("properties", None) + self.measurements = kwargs.get("measurements", None) class StackFrame(msrest.serialization.Model): @@ -817,24 +787,21 @@ class StackFrame(msrest.serialization.Model): """ _validation = { - 'level': {'required': True}, - 'method': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'assembly': {'max_length': 1024, 'min_length': 0}, - 'file_name': {'max_length': 1024, 'min_length': 0}, + "level": {"required": True}, + "method": {"required": True, "max_length": 1024, "min_length": 0}, + "assembly": {"max_length": 1024, "min_length": 0}, + "file_name": {"max_length": 1024, "min_length": 0}, } _attribute_map = { - 'level': {'key': 'level', 'type': 'int'}, - 'method': {'key': 'method', 'type': 'str'}, - 'assembly': {'key': 'assembly', 'type': 'str'}, - 'file_name': {'key': 'fileName', 'type': 'str'}, - 'line': {'key': 'line', 'type': 'int'}, + "level": {"key": "level", "type": "int"}, + "method": {"key": "method", "type": "str"}, + "assembly": {"key": "assembly", "type": "str"}, + "file_name": {"key": "fileName", "type": "str"}, + "line": {"key": "line", "type": "int"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword level: Required. :paramtype level: int @@ -848,11 +815,11 @@ def __init__( :paramtype line: int """ super(StackFrame, self).__init__(**kwargs) - self.level = kwargs['level'] - self.method = kwargs['method'] - self.assembly = kwargs.get('assembly', None) - self.file_name = kwargs.get('file_name', None) - self.line = kwargs.get('line', None) + self.level = kwargs["level"] + self.method = kwargs["method"] + self.assembly = kwargs.get("assembly", None) + self.file_name = kwargs.get("file_name", None) + self.line = kwargs.get("line", None) class TelemetryErrorDetails(msrest.serialization.Model): @@ -867,15 +834,12 @@ class TelemetryErrorDetails(msrest.serialization.Model): """ _attribute_map = { - 'index': {'key': 'index', 'type': 'int'}, - 'status_code': {'key': 'statusCode', 'type': 'int'}, - 'message': {'key': 'message', 'type': 'str'}, + "index": {"key": "index", "type": "int"}, + "status_code": {"key": "statusCode", "type": "int"}, + "message": {"key": "message", "type": "str"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword index: The index in the original payload of the item. :paramtype index: int @@ -885,9 +849,9 @@ def __init__( :paramtype message: str """ super(TelemetryErrorDetails, self).__init__(**kwargs) - self.index = kwargs.get('index', None) - self.status_code = kwargs.get('status_code', None) - self.message = kwargs.get('message', None) + self.index = kwargs.get("index", None) + self.status_code = kwargs.get("status_code", None) + self.message = kwargs.get("message", None) class TelemetryEventData(MonitorDomain): @@ -910,22 +874,19 @@ class TelemetryEventData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'name': {'required': True, 'max_length': 512, 'min_length': 0}, + "version": {"required": True}, + "name": {"required": True, "max_length": 512, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'name': {'key': 'name', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -941,9 +902,9 @@ def __init__( :paramtype measurements: dict[str, float] """ super(TelemetryEventData, self).__init__(**kwargs) - self.name = kwargs['name'] - self.properties = kwargs.get('properties', None) - self.measurements = kwargs.get('measurements', None) + self.name = kwargs["name"] + self.properties = kwargs.get("properties", None) + self.measurements = kwargs.get("measurements", None) class TelemetryExceptionData(MonitorDomain): @@ -972,25 +933,22 @@ class TelemetryExceptionData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'exceptions': {'required': True}, - 'problem_id': {'max_length': 1024, 'min_length': 0}, + "version": {"required": True}, + "exceptions": {"required": True}, + "problem_id": {"max_length": 1024, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'exceptions': {'key': 'exceptions', 'type': '[TelemetryExceptionDetails]'}, - 'severity_level': {'key': 'severityLevel', 'type': 'str'}, - 'problem_id': {'key': 'problemId', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "exceptions": {"key": "exceptions", "type": "[TelemetryExceptionDetails]"}, + "severity_level": {"key": "severityLevel", "type": "str"}, + "problem_id": {"key": "problemId", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -1012,11 +970,11 @@ def __init__( :paramtype measurements: dict[str, float] """ super(TelemetryExceptionData, self).__init__(**kwargs) - self.exceptions = kwargs['exceptions'] - self.severity_level = kwargs.get('severity_level', None) - self.problem_id = kwargs.get('problem_id', None) - self.properties = kwargs.get('properties', None) - self.measurements = kwargs.get('measurements', None) + self.exceptions = kwargs["exceptions"] + self.severity_level = kwargs.get("severity_level", None) + self.problem_id = kwargs.get("problem_id", None) + self.properties = kwargs.get("properties", None) + self.measurements = kwargs.get("measurements", None) class TelemetryExceptionDetails(msrest.serialization.Model): @@ -1044,25 +1002,22 @@ class TelemetryExceptionDetails(msrest.serialization.Model): """ _validation = { - 'type_name': {'max_length': 1024, 'min_length': 0}, - 'message': {'required': True, 'max_length': 32768, 'min_length': 0}, - 'stack': {'max_length': 32768, 'min_length': 0}, + "type_name": {"max_length": 1024, "min_length": 0}, + "message": {"required": True, "max_length": 32768, "min_length": 0}, + "stack": {"max_length": 32768, "min_length": 0}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'int'}, - 'outer_id': {'key': 'outerId', 'type': 'int'}, - 'type_name': {'key': 'typeName', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'has_full_stack': {'key': 'hasFullStack', 'type': 'bool'}, - 'stack': {'key': 'stack', 'type': 'str'}, - 'parsed_stack': {'key': 'parsedStack', 'type': '[StackFrame]'}, + "id": {"key": "id", "type": "int"}, + "outer_id": {"key": "outerId", "type": "int"}, + "type_name": {"key": "typeName", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "has_full_stack": {"key": "hasFullStack", "type": "bool"}, + "stack": {"key": "stack", "type": "str"}, + "parsed_stack": {"key": "parsedStack", "type": "[StackFrame]"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword id: In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. @@ -1083,13 +1038,13 @@ def __init__( :paramtype parsed_stack: list[~azure_monitor_client.models.StackFrame] """ super(TelemetryExceptionDetails, self).__init__(**kwargs) - self.id = kwargs.get('id', None) - self.outer_id = kwargs.get('outer_id', None) - self.type_name = kwargs.get('type_name', None) - self.message = kwargs['message'] - self.has_full_stack = kwargs.get('has_full_stack', True) - self.stack = kwargs.get('stack', None) - self.parsed_stack = kwargs.get('parsed_stack', None) + self.id = kwargs.get("id", None) + self.outer_id = kwargs.get("outer_id", None) + self.type_name = kwargs.get("type_name", None) + self.message = kwargs["message"] + self.has_full_stack = kwargs.get("has_full_stack", True) + self.stack = kwargs.get("stack", None) + self.parsed_stack = kwargs.get("parsed_stack", None) class TelemetryItem(msrest.serialization.Model): @@ -1125,26 +1080,23 @@ class TelemetryItem(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, - 'time': {'required': True}, - 'sequence': {'max_length': 64, 'min_length': 0}, + "name": {"required": True}, + "time": {"required": True}, + "sequence": {"max_length": 64, "min_length": 0}, } _attribute_map = { - 'version': {'key': 'ver', 'type': 'int'}, - 'name': {'key': 'name', 'type': 'str'}, - 'time': {'key': 'time', 'type': 'iso-8601'}, - 'sample_rate': {'key': 'sampleRate', 'type': 'float'}, - 'sequence': {'key': 'seq', 'type': 'str'}, - 'instrumentation_key': {'key': 'iKey', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'data': {'key': 'data', 'type': 'MonitorBase'}, + "version": {"key": "ver", "type": "int"}, + "name": {"key": "name", "type": "str"}, + "time": {"key": "time", "type": "iso-8601"}, + "sample_rate": {"key": "sampleRate", "type": "float"}, + "sequence": {"key": "seq", "type": "str"}, + "instrumentation_key": {"key": "iKey", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "data": {"key": "data", "type": "MonitorBase"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword version: Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. @@ -1173,14 +1125,14 @@ def __init__( :paramtype data: ~azure_monitor_client.models.MonitorBase """ super(TelemetryItem, self).__init__(**kwargs) - self.version = kwargs.get('version', 1) - self.name = kwargs['name'] - self.time = kwargs['time'] - self.sample_rate = kwargs.get('sample_rate', 100) - self.sequence = kwargs.get('sequence', None) - self.instrumentation_key = kwargs.get('instrumentation_key', None) - self.tags = kwargs.get('tags', None) - self.data = kwargs.get('data', None) + self.version = kwargs.get("version", 1) + self.name = kwargs["name"] + self.time = kwargs["time"] + self.sample_rate = kwargs.get("sample_rate", 100) + self.sequence = kwargs.get("sequence", None) + self.instrumentation_key = kwargs.get("instrumentation_key", None) + self.tags = kwargs.get("tags", None) + self.data = kwargs.get("data", None) class TrackResponse(msrest.serialization.Model): @@ -1195,15 +1147,12 @@ class TrackResponse(msrest.serialization.Model): """ _attribute_map = { - 'items_received': {'key': 'itemsReceived', 'type': 'int'}, - 'items_accepted': {'key': 'itemsAccepted', 'type': 'int'}, - 'errors': {'key': 'errors', 'type': '[TelemetryErrorDetails]'}, + "items_received": {"key": "itemsReceived", "type": "int"}, + "items_accepted": {"key": "itemsAccepted", "type": "int"}, + "errors": {"key": "errors", "type": "[TelemetryErrorDetails]"}, } - def __init__( - self, - **kwargs - ): + def __init__(self, **kwargs): """ :keyword items_received: The number of items received. :paramtype items_received: int @@ -1213,6 +1162,6 @@ def __init__( :paramtype errors: list[~azure_monitor_client.models.TelemetryErrorDetails] """ super(TrackResponse, self).__init__(**kwargs) - self.items_received = kwargs.get('items_received', None) - self.items_accepted = kwargs.get('items_accepted', None) - self.errors = kwargs.get('errors', None) + self.items_received = kwargs.get("items_received", None) + self.items_accepted = kwargs.get("items_accepted", None) + self.errors = kwargs.get("errors", None) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_models_py3.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_models_py3.py index 6c895a27a62b..9741154cfb3c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_models_py3.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/models/_models_py3.py @@ -28,21 +28,15 @@ class MonitorDomain(msrest.serialization.Model): """ _validation = { - 'version': {'required': True}, + "version": {"required": True}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, } - def __init__( - self, - *, - version: int = 2, - additional_properties: Optional[Dict[str, Any]] = None, - **kwargs - ): + def __init__(self, *, version: int = 2, additional_properties: Optional[Dict[str, Any]] = None, **kwargs): """ :keyword additional_properties: Unmatched properties from the message are deserialized to this collection. @@ -85,26 +79,26 @@ class AvailabilityData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'required': True, 'max_length': 512, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'duration': {'required': True}, - 'success': {'required': True}, - 'run_location': {'max_length': 1024, 'min_length': 0}, - 'message': {'max_length': 8192, 'min_length': 0}, + "version": {"required": True}, + "id": {"required": True, "max_length": 512, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "duration": {"required": True}, + "success": {"required": True}, + "run_location": {"max_length": 1024, "min_length": 0}, + "message": {"max_length": 8192, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'success': {'key': 'success', 'type': 'bool'}, - 'run_location': {'key': 'runLocation', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "success": {"key": "success", "type": "bool"}, + "run_location": {"key": "runLocation", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } def __init__( @@ -180,17 +174,17 @@ class MessageData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'message': {'required': True, 'max_length': 32768, 'min_length': 0}, + "version": {"required": True}, + "message": {"required": True, "max_length": 32768, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'message': {'key': 'message', 'type': 'str'}, - 'severity_level': {'key': 'severityLevel', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "message": {"key": "message", "type": "str"}, + "severity_level": {"key": "severityLevel", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } def __init__( @@ -254,20 +248,20 @@ class MetricDataPoint(msrest.serialization.Model): """ _validation = { - 'namespace': {'max_length': 256, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'value': {'required': True}, + "namespace": {"max_length": 256, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "value": {"required": True}, } _attribute_map = { - 'namespace': {'key': 'ns', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'data_point_type': {'key': 'kind', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'float'}, - 'count': {'key': 'count', 'type': 'int'}, - 'min': {'key': 'min', 'type': 'float'}, - 'max': {'key': 'max', 'type': 'float'}, - 'std_dev': {'key': 'stdDev', 'type': 'float'}, + "namespace": {"key": "ns", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "data_point_type": {"key": "kind", "type": "str"}, + "value": {"key": "value", "type": "float"}, + "count": {"key": "count", "type": "int"}, + "min": {"key": "min", "type": "float"}, + "max": {"key": "max", "type": "float"}, + "std_dev": {"key": "stdDev", "type": "float"}, } def __init__( @@ -334,15 +328,15 @@ class MetricsData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'metrics': {'required': True}, + "version": {"required": True}, + "metrics": {"required": True}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'metrics': {'key': 'metrics', 'type': '[MetricDataPoint]'}, - 'properties': {'key': 'properties', 'type': '{str}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "metrics": {"key": "metrics", "type": "[MetricDataPoint]"}, + "properties": {"key": "properties", "type": "{str}"}, } def __init__( @@ -383,17 +377,11 @@ class MonitorBase(msrest.serialization.Model): """ _attribute_map = { - 'base_type': {'key': 'baseType', 'type': 'str'}, - 'base_data': {'key': 'baseData', 'type': 'MonitorDomain'}, + "base_type": {"key": "baseType", "type": "str"}, + "base_data": {"key": "baseData", "type": "MonitorDomain"}, } - def __init__( - self, - *, - base_type: Optional[str] = None, - base_data: Optional["MonitorDomain"] = None, - **kwargs - ): + def __init__(self, *, base_type: Optional[str] = None, base_data: Optional["MonitorDomain"] = None, **kwargs): """ :keyword base_type: Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. @@ -438,23 +426,23 @@ class PageViewData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'required': True, 'max_length': 512, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'url': {'max_length': 2048, 'min_length': 0}, - 'referred_uri': {'max_length': 2048, 'min_length': 0}, + "version": {"required": True}, + "id": {"required": True, "max_length": 512, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "url": {"max_length": 2048, "min_length": 0}, + "referred_uri": {"max_length": 2048, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'referred_uri': {'key': 'referredUri', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "url": {"key": "url", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "referred_uri": {"key": "referredUri", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } def __init__( @@ -550,26 +538,26 @@ class PageViewPerfData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'required': True, 'max_length': 512, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'url': {'max_length': 2048, 'min_length': 0}, + "version": {"required": True}, + "id": {"required": True, "max_length": 512, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "url": {"max_length": 2048, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'perf_total': {'key': 'perfTotal', 'type': 'str'}, - 'network_connect': {'key': 'networkConnect', 'type': 'str'}, - 'sent_request': {'key': 'sentRequest', 'type': 'str'}, - 'received_response': {'key': 'receivedResponse', 'type': 'str'}, - 'dom_processing': {'key': 'domProcessing', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "url": {"key": "url", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "perf_total": {"key": "perfTotal", "type": "str"}, + "network_connect": {"key": "networkConnect", "type": "str"}, + "sent_request": {"key": "sentRequest", "type": "str"}, + "received_response": {"key": "receivedResponse", "type": "str"}, + "dom_processing": {"key": "domProcessing", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } def __init__( @@ -682,29 +670,29 @@ class RemoteDependencyData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'max_length': 512, 'min_length': 0}, - 'name': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'result_code': {'max_length': 1024, 'min_length': 0}, - 'data': {'max_length': 8192, 'min_length': 0}, - 'type': {'max_length': 1024, 'min_length': 0}, - 'target': {'max_length': 1024, 'min_length': 0}, - 'duration': {'required': True}, + "version": {"required": True}, + "id": {"max_length": 512, "min_length": 0}, + "name": {"required": True, "max_length": 1024, "min_length": 0}, + "result_code": {"max_length": 1024, "min_length": 0}, + "data": {"max_length": 8192, "min_length": 0}, + "type": {"max_length": 1024, "min_length": 0}, + "target": {"max_length": 1024, "min_length": 0}, + "duration": {"required": True}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'result_code': {'key': 'resultCode', 'type': 'str'}, - 'data': {'key': 'data', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'success': {'key': 'success', 'type': 'bool'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "result_code": {"key": "resultCode", "type": "str"}, + "data": {"key": "data", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "success": {"key": "success", "type": "bool"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } def __init__( @@ -758,7 +746,9 @@ def __init__( :keyword measurements: Collection of custom measurements. :paramtype measurements: dict[str, float] """ - super(RemoteDependencyData, self).__init__(additional_properties=additional_properties, version=version, **kwargs) + super(RemoteDependencyData, self).__init__( + additional_properties=additional_properties, version=version, **kwargs + ) self.id = id self.name = name self.result_code = result_code @@ -808,28 +798,28 @@ class RequestData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'id': {'required': True, 'max_length': 512, 'min_length': 0}, - 'name': {'max_length': 1024, 'min_length': 0}, - 'duration': {'required': True}, - 'success': {'required': True}, - 'response_code': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'source': {'max_length': 1024, 'min_length': 0}, - 'url': {'max_length': 2048, 'min_length': 0}, + "version": {"required": True}, + "id": {"required": True, "max_length": 512, "min_length": 0}, + "name": {"max_length": 1024, "min_length": 0}, + "duration": {"required": True}, + "success": {"required": True}, + "response_code": {"required": True, "max_length": 1024, "min_length": 0}, + "source": {"max_length": 1024, "min_length": 0}, + "url": {"max_length": 2048, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'duration': {'key': 'duration', 'type': 'str'}, - 'success': {'key': 'success', 'type': 'bool'}, - 'response_code': {'key': 'responseCode', 'type': 'str'}, - 'source': {'key': 'source', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "duration": {"key": "duration", "type": "str"}, + "success": {"key": "success", "type": "bool"}, + "response_code": {"key": "responseCode", "type": "str"}, + "source": {"key": "source", "type": "str"}, + "url": {"key": "url", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } def __init__( @@ -909,18 +899,18 @@ class StackFrame(msrest.serialization.Model): """ _validation = { - 'level': {'required': True}, - 'method': {'required': True, 'max_length': 1024, 'min_length': 0}, - 'assembly': {'max_length': 1024, 'min_length': 0}, - 'file_name': {'max_length': 1024, 'min_length': 0}, + "level": {"required": True}, + "method": {"required": True, "max_length": 1024, "min_length": 0}, + "assembly": {"max_length": 1024, "min_length": 0}, + "file_name": {"max_length": 1024, "min_length": 0}, } _attribute_map = { - 'level': {'key': 'level', 'type': 'int'}, - 'method': {'key': 'method', 'type': 'str'}, - 'assembly': {'key': 'assembly', 'type': 'str'}, - 'file_name': {'key': 'fileName', 'type': 'str'}, - 'line': {'key': 'line', 'type': 'int'}, + "level": {"key": "level", "type": "int"}, + "method": {"key": "method", "type": "str"}, + "assembly": {"key": "assembly", "type": "str"}, + "file_name": {"key": "fileName", "type": "str"}, + "line": {"key": "line", "type": "int"}, } def __init__( @@ -965,18 +955,13 @@ class TelemetryErrorDetails(msrest.serialization.Model): """ _attribute_map = { - 'index': {'key': 'index', 'type': 'int'}, - 'status_code': {'key': 'statusCode', 'type': 'int'}, - 'message': {'key': 'message', 'type': 'str'}, + "index": {"key": "index", "type": "int"}, + "status_code": {"key": "statusCode", "type": "int"}, + "message": {"key": "message", "type": "str"}, } def __init__( - self, - *, - index: Optional[int] = None, - status_code: Optional[int] = None, - message: Optional[str] = None, - **kwargs + self, *, index: Optional[int] = None, status_code: Optional[int] = None, message: Optional[str] = None, **kwargs ): """ :keyword index: The index in the original payload of the item. @@ -1012,16 +997,16 @@ class TelemetryEventData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'name': {'required': True, 'max_length': 512, 'min_length': 0}, + "version": {"required": True}, + "name": {"required": True, "max_length": 512, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'name': {'key': 'name', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "name": {"key": "name", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } def __init__( @@ -1080,19 +1065,19 @@ class TelemetryExceptionData(MonitorDomain): """ _validation = { - 'version': {'required': True}, - 'exceptions': {'required': True}, - 'problem_id': {'max_length': 1024, 'min_length': 0}, + "version": {"required": True}, + "exceptions": {"required": True}, + "problem_id": {"max_length": 1024, "min_length": 0}, } _attribute_map = { - 'additional_properties': {'key': '', 'type': '{object}'}, - 'version': {'key': 'ver', 'type': 'int'}, - 'exceptions': {'key': 'exceptions', 'type': '[TelemetryExceptionDetails]'}, - 'severity_level': {'key': 'severityLevel', 'type': 'str'}, - 'problem_id': {'key': 'problemId', 'type': 'str'}, - 'properties': {'key': 'properties', 'type': '{str}'}, - 'measurements': {'key': 'measurements', 'type': '{float}'}, + "additional_properties": {"key": "", "type": "{object}"}, + "version": {"key": "ver", "type": "int"}, + "exceptions": {"key": "exceptions", "type": "[TelemetryExceptionDetails]"}, + "severity_level": {"key": "severityLevel", "type": "str"}, + "problem_id": {"key": "problemId", "type": "str"}, + "properties": {"key": "properties", "type": "{str}"}, + "measurements": {"key": "measurements", "type": "{float}"}, } def __init__( @@ -1127,7 +1112,9 @@ def __init__( :keyword measurements: Collection of custom measurements. :paramtype measurements: dict[str, float] """ - super(TelemetryExceptionData, self).__init__(additional_properties=additional_properties, version=version, **kwargs) + super(TelemetryExceptionData, self).__init__( + additional_properties=additional_properties, version=version, **kwargs + ) self.exceptions = exceptions self.severity_level = severity_level self.problem_id = problem_id @@ -1160,19 +1147,19 @@ class TelemetryExceptionDetails(msrest.serialization.Model): """ _validation = { - 'type_name': {'max_length': 1024, 'min_length': 0}, - 'message': {'required': True, 'max_length': 32768, 'min_length': 0}, - 'stack': {'max_length': 32768, 'min_length': 0}, + "type_name": {"max_length": 1024, "min_length": 0}, + "message": {"required": True, "max_length": 32768, "min_length": 0}, + "stack": {"max_length": 32768, "min_length": 0}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'int'}, - 'outer_id': {'key': 'outerId', 'type': 'int'}, - 'type_name': {'key': 'typeName', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'has_full_stack': {'key': 'hasFullStack', 'type': 'bool'}, - 'stack': {'key': 'stack', 'type': 'str'}, - 'parsed_stack': {'key': 'parsedStack', 'type': '[StackFrame]'}, + "id": {"key": "id", "type": "int"}, + "outer_id": {"key": "outerId", "type": "int"}, + "type_name": {"key": "typeName", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "has_full_stack": {"key": "hasFullStack", "type": "bool"}, + "stack": {"key": "stack", "type": "str"}, + "parsed_stack": {"key": "parsedStack", "type": "[StackFrame]"}, } def __init__( @@ -1249,20 +1236,20 @@ class TelemetryItem(msrest.serialization.Model): """ _validation = { - 'name': {'required': True}, - 'time': {'required': True}, - 'sequence': {'max_length': 64, 'min_length': 0}, + "name": {"required": True}, + "time": {"required": True}, + "sequence": {"max_length": 64, "min_length": 0}, } _attribute_map = { - 'version': {'key': 'ver', 'type': 'int'}, - 'name': {'key': 'name', 'type': 'str'}, - 'time': {'key': 'time', 'type': 'iso-8601'}, - 'sample_rate': {'key': 'sampleRate', 'type': 'float'}, - 'sequence': {'key': 'seq', 'type': 'str'}, - 'instrumentation_key': {'key': 'iKey', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'data': {'key': 'data', 'type': 'MonitorBase'}, + "version": {"key": "ver", "type": "int"}, + "name": {"key": "name", "type": "str"}, + "time": {"key": "time", "type": "iso-8601"}, + "sample_rate": {"key": "sampleRate", "type": "float"}, + "sequence": {"key": "seq", "type": "str"}, + "instrumentation_key": {"key": "iKey", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "data": {"key": "data", "type": "MonitorBase"}, } def __init__( @@ -1328,9 +1315,9 @@ class TrackResponse(msrest.serialization.Model): """ _attribute_map = { - 'items_received': {'key': 'itemsReceived', 'type': 'int'}, - 'items_accepted': {'key': 'itemsAccepted', 'type': 'int'}, - 'errors': {'key': 'errors', 'type': '[TelemetryErrorDetails]'}, + "items_received": {"key": "itemsReceived", "type": "int"}, + "items_accepted": {"key": "itemsAccepted", "type": "int"}, + "errors": {"key": "errors", "type": "[TelemetryErrorDetails]"}, } def __init__( diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/operations/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/operations/__init__.py index 30cdb38f8dbb..a1b6ce78bd5c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/operations/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/operations/__init__.py @@ -9,5 +9,5 @@ from ._azure_monitor_client_operations import AzureMonitorClientOperationsMixin __all__ = [ - 'AzureMonitorClientOperationsMixin', + "AzureMonitorClientOperationsMixin", ] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/operations/_azure_monitor_client_operations.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/operations/_azure_monitor_client_operations.py index 4c4b1104ade5..6bc3c37e9233 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/operations/_azure_monitor_client_operations.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_generated/operations/_azure_monitor_client_operations.py @@ -10,7 +10,13 @@ from msrest import Serializer -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest @@ -21,7 +27,8 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, List, Optional, TypeVar - T = TypeVar('T') + + T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() @@ -51,6 +58,7 @@ def build_track_request( **kwargs ) + # fmt: on class AzureMonitorClientOperationsMixin(object): @@ -71,38 +79,46 @@ def track( :rtype: ~azure_monitor_client.models.TrackResponse :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.TrackResponse"] + cls = kwargs.pop("cls", None) # type: ClsType["_models.TrackResponse"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, - 400: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), - 402: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), - 429: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), - 500: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), - 503: lambda response: HttpResponseError(response=response, model=self._deserialize(_models.TrackResponse, response)), + 400: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), + 402: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), + 429: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), + 500: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), + 503: lambda response: HttpResponseError( + response=response, model=self._deserialize(_models.TrackResponse, response) + ), } - error_map.update(kwargs.pop('error_map', {})) + error_map.update(kwargs.pop("error_map", {})) - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] + content_type = kwargs.pop("content_type", "application/json") # type: Optional[str] - _json = self._serialize.body(body, '[TelemetryItem]') + _json = self._serialize.body(body, "[TelemetryItem]") request = build_track_request( content_type=content_type, json=_json, - template_url=self.track.metadata['url'], + template_url=self.track.metadata["url"], ) request = _convert_request(request) path_format_arguments = { - "Host": self._serialize.url("self._config.host", self._config.host, 'str', skip_quote=True), + "Host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), } request.url = self._client.format_url(request.url, **path_format_arguments) pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access - request, - stream=False, - **kwargs + request, stream=False, **kwargs ) response = pipeline_response.http_response @@ -111,15 +127,14 @@ def track( raise HttpResponseError(response=response) if response.status_code == 200: - deserialized = self._deserialize('TrackResponse', pipeline_response) + deserialized = self._deserialize("TrackResponse", pipeline_response) if response.status_code == 206: - deserialized = self._deserialize('TrackResponse', pipeline_response) + deserialized = self._deserialize("TrackResponse", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized - track.metadata = {'url': "/track"} # type: ignore - + track.metadata = {"url": "/track"} # type: ignore diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_constants.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_constants.py index f19c1f7a8049..e95b91a045f2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_constants.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_constants.py @@ -17,7 +17,10 @@ _REQUEST_DURATION_NAME = ("azuremonitor.requestduration", "\\ApplicationInsights\\Request Duration") # Dependency _DEPENDENCY_RATE_NAME = ("azuremonitor.dependencycallssec", "\\ApplicationInsights\\Dependency Calls/Sec") -_DEPENDENCY_FAILURE_RATE_NAME = ("azuremonitor.dependencycallsfailedsec", "\\ApplicationInsights\\Dependency Calls Failed/Sec") # pylint: disable=line-too-long +_DEPENDENCY_FAILURE_RATE_NAME = ( + "azuremonitor.dependencycallsfailedsec", + "\\ApplicationInsights\\Dependency Calls Failed/Sec", +) # pylint: disable=line-too-long _DEPENDENCY_DURATION_NAME = ("azuremonitor.dependencycallduration", "\\ApplicationInsights\\Dependency Call Duration") # Exception _EXCEPTION_RATE_NAME = ("azuremonitor.exceptionssec", "\\ApplicationInsights\\Exceptions/Sec") @@ -44,6 +47,7 @@ _LONG_PING_INTERVAL_SECONDS = 60 _POST_CANCEL_INTERVAL_SECONDS = 20 + # Live metrics data types class _DocumentIngressDocumentType(Enum): Request = "Request" @@ -52,6 +56,7 @@ class _DocumentIngressDocumentType(Enum): Event = "Event" Trace = "Trace" + # Response Headers _QUICKPULSE_ETAG_HEADER_NAME = "x-ms-qps-configuration-etag" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_exporter.py index 9633a4dd0f84..2b0bbe5b7464 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_exporter.py @@ -67,6 +67,7 @@ class _Response: """Response that encapsulates pipeline response and response headers from QuickPulse client. """ + def __init__(self, pipeline_response, deserialized, response_headers): self._pipeline_response = pipeline_response self._deserialized = deserialized @@ -79,7 +80,7 @@ class _UnsuccessfulQuickPulsePostError(Exception): class _QuickpulseExporter(MetricExporter): - def __init__(self, **kwargs: Any) -> None: + def __init__(self, **kwargs: Any) -> None: # pylint: disable=unused-argument """Metric exporter for Quickpulse. :param str connection_string: The connection string used for your Application Insights resource. @@ -87,11 +88,11 @@ def __init__(self, **kwargs: Any) -> None: ClientSecretCredential, used for Azure Active Directory (AAD) authentication. Defaults to None. :rtype: None """ - parsed_connection_string = ConnectionStringParser(kwargs.get('connection_string')) + parsed_connection_string = ConnectionStringParser(kwargs.get("connection_string")) self._live_endpoint = parsed_connection_string.live_endpoint self._instrumentation_key = parsed_connection_string.instrumentation_key - self._credential = kwargs.get('credential') + self._credential = kwargs.get("credential") config = QuickpulseClientConfiguration(credential=self._credential) # type: ignore qp_redirect_policy = _QuickpulseRedirectPolicy(permit_redirects=False) policies = [ @@ -107,9 +108,7 @@ def __init__(self, **kwargs: Any) -> None: # DistributedTracingPolicy(), ] self._client = QuickpulseClient( - credential=self._credential, # type: ignore - endpoint=self._live_endpoint, - policies=policies + credential=self._credential, endpoint=self._live_endpoint, policies=policies # type: ignore ) # Create a weakref of the client to the redirect policy so the endpoint can be # dynamically modified if redirect does occur @@ -117,7 +116,7 @@ def __init__(self, **kwargs: Any) -> None: MetricExporter.__init__( self, - preferred_temporality=_QUICKPULSE_METRIC_TEMPORALITIES, # type: ignore + preferred_temporality=_QUICKPULSE_METRIC_TEMPORALITIES, # type: ignore ) def export( @@ -158,7 +157,9 @@ def export( # If no response, assume unsuccessful result = MetricExportResult.FAILURE else: - header = post_response._response_headers.get(_QUICKPULSE_SUBSCRIBED_HEADER_NAME) # pylint: disable=protected-access + header = post_response._response_headers.get( # pylint: disable=protected-access + _QUICKPULSE_SUBSCRIBED_HEADER_NAME + ) if header != "true": # User leaving the live metrics page will be treated as an unsuccessful result = MetricExportResult.FAILURE @@ -184,7 +185,6 @@ def force_flush( """ return True - def shutdown( self, timeout_millis: float = 30_000, # pylint: disable=unused-argument @@ -198,7 +198,6 @@ def shutdown( :type timeout_millis: float """ - def _ping(self, monitoring_data_point: MonitoringDataPoint) -> Optional[_Response]: ping_response = None token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True)) @@ -252,22 +251,28 @@ def _ticker(self) -> None: self._base_monitoring_data_point, ) if ping_response: - header = ping_response._response_headers.get(_QUICKPULSE_SUBSCRIBED_HEADER_NAME) # pylint: disable=protected-access + header = ping_response._response_headers.get( # pylint: disable=protected-access + _QUICKPULSE_SUBSCRIBED_HEADER_NAME + ) if header and header == "true": # Switch state to post if subscribed _set_global_quickpulse_state(_QuickpulseState.POST_SHORT) self._elapsed_num_seconds = 0 else: # Backoff after _LONG_PING_INTERVAL_SECONDS (60s) of no successful requests - if _get_global_quickpulse_state() is _QuickpulseState.PING_SHORT and \ - self._elapsed_num_seconds >= _LONG_PING_INTERVAL_SECONDS: + if ( + _get_global_quickpulse_state() is _QuickpulseState.PING_SHORT + and self._elapsed_num_seconds >= _LONG_PING_INTERVAL_SECONDS + ): _set_global_quickpulse_state(_QuickpulseState.PING_LONG) # TODO: Implement redirect else: # Erroneous ping responses instigate backoff logic # Backoff after _LONG_PING_INTERVAL_SECONDS (60s) of no successful requests - if _get_global_quickpulse_state() is _QuickpulseState.PING_SHORT and \ - self._elapsed_num_seconds >= _LONG_PING_INTERVAL_SECONDS: + if ( + _get_global_quickpulse_state() is _QuickpulseState.PING_SHORT + and self._elapsed_num_seconds >= _LONG_PING_INTERVAL_SECONDS + ): _set_global_quickpulse_state(_QuickpulseState.PING_LONG) else: try: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_live_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_live_metrics.py index 3acb09e062b1..08be036d8c29 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_live_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_live_metrics.py @@ -65,6 +65,7 @@ PROCESS = psutil.Process() NUM_CPUS = psutil.cpu_count() + def enable_live_metrics(**kwargs: Any) -> None: # pylint: disable=C4758 """Live metrics entry point. @@ -85,7 +86,7 @@ def __init__(self, **kwargs: Any) -> None: _set_global_quickpulse_state(_QuickpulseState.PING_SHORT) self._exporter = _QuickpulseExporter(**kwargs) part_a_fields = {} - resource = kwargs.get('resource') + resource = kwargs.get("resource") if not resource: resource = Resource.create({}) part_a_fields = _populate_part_a_fields(resource) @@ -108,42 +109,28 @@ def __init__(self, **kwargs: Any) -> None: self._meter = self._meter_provider.get_meter("azure_monitor_live_metrics") self._request_duration = self._meter.create_histogram( - _REQUEST_DURATION_NAME[0], - "ms", - "live metrics avg request duration in ms" + _REQUEST_DURATION_NAME[0], "ms", "live metrics avg request duration in ms" ) self._dependency_duration = self._meter.create_histogram( - _DEPENDENCY_DURATION_NAME[0], - "ms", - "live metrics avg dependency duration in ms" + _DEPENDENCY_DURATION_NAME[0], "ms", "live metrics avg dependency duration in ms" ) # We use a counter to represent rates per second because collection # interval is one second so we simply need the number of requests # within the collection interval self._request_rate_counter = self._meter.create_counter( - _REQUEST_RATE_NAME[0], - "req/sec", - "live metrics request rate per second" + _REQUEST_RATE_NAME[0], "req/sec", "live metrics request rate per second" ) self._request_failed_rate_counter = self._meter.create_counter( - _REQUEST_FAILURE_RATE_NAME[0], - "req/sec", - "live metrics request failed rate per second" + _REQUEST_FAILURE_RATE_NAME[0], "req/sec", "live metrics request failed rate per second" ) self._dependency_rate_counter = self._meter.create_counter( - _DEPENDENCY_RATE_NAME[0], - "dep/sec", - "live metrics dependency rate per second" + _DEPENDENCY_RATE_NAME[0], "dep/sec", "live metrics dependency rate per second" ) self._dependency_failure_rate_counter = self._meter.create_counter( - _DEPENDENCY_FAILURE_RATE_NAME[0], - "dep/sec", - "live metrics dependency failure rate per second" + _DEPENDENCY_FAILURE_RATE_NAME[0], "dep/sec", "live metrics dependency failure rate per second" ) self._exception_rate_counter = self._meter.create_counter( - _EXCEPTION_RATE_NAME[0], - "exc/sec", - "live metrics exception rate per second" + _EXCEPTION_RATE_NAME[0], "exc/sec", "live metrics exception rate per second" ) self._process_memory_gauge_old = self._meter.create_observable_gauge( _COMMITTED_BYTES_NAME[0], @@ -238,4 +225,5 @@ def _get_process_time_normalized_old(options: CallbackOptions) -> Iterable[Obser def _get_process_time_normalized(options: CallbackOptions) -> Iterable[Observation]: yield Observation(_get_quickpulse_last_process_cpu(), {}) + # cSpell:enable diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_policy.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_policy.py index 3e2af24d9f89..b0d84aea4302 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_policy.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_policy.py @@ -22,7 +22,7 @@ def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) # Gets the redirect location from header - def get_redirect_location(self, response: PipelineResponse) -> Optional[str] : + def get_redirect_location(self, response: PipelineResponse) -> Optional[str]: redirect_location = response.http_response.headers.get(_QUICKPULSE_REDIRECT_HEADER_NAME) qp_client = None if redirect_location: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_processor.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_processor.py index 2e18253976fb..e31b0be77169 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_processor.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_processor.py @@ -14,13 +14,13 @@ def emit(self, log_data: LogData) -> None: qpm = _QuickpulseManager._instance if qpm: qpm._record_log_record(log_data) - super().emit(log_data) + super().emit(log_data) # type: ignore[safe-super] def shutdown(self): pass def force_flush(self, timeout_millis: int = 30000): - super().force_flush(timeout_millis=timeout_millis) + super().force_flush(timeout_millis=timeout_millis) # type: ignore[safe-super] # pylint: disable=protected-access diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_state.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_state.py index b5934b13bef0..fddf58af19f9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_state.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_state.py @@ -16,6 +16,7 @@ class _QuickpulseState(Enum): """Current state of quickpulse service. The numerical value represents the ping/post interval in ms for those states. """ + OFFLINE = 0 PING_SHORT = _SHORT_PING_INTERVAL_SECONDS PING_LONG = _LONG_PING_INTERVAL_SECONDS @@ -28,6 +29,7 @@ class _QuickpulseState(Enum): _QUICKPULSE_PROCESS_ELAPSED_TIME = datetime.now() _QUICKPULSE_LAST_PROCESS_CPU = 0.0 + def _set_global_quickpulse_state(state: _QuickpulseState) -> None: # pylint: disable=global-statement global _GLOBAL_QUICKPULSE_STATE @@ -73,10 +75,7 @@ def is_quickpulse_enabled() -> bool: def _is_ping_state() -> bool: - return _get_global_quickpulse_state() in ( - _QuickpulseState.PING_SHORT, - _QuickpulseState.PING_LONG - ) + return _get_global_quickpulse_state() in (_QuickpulseState.PING_SHORT, _QuickpulseState.PING_LONG) def _is_post_state(): diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_utils.py index 111600bd5f47..dca763a7f260 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_utils.py @@ -27,6 +27,8 @@ Request as RequestDocument, Trace as TraceDocument, ) + + def _metric_to_quick_pulse_data_points( # pylint: disable=too-many-nested-blocks metrics_data: OTMetricsData, base_monitoring_data_point: MonitoringDataPoint, @@ -45,9 +47,7 @@ def _metric_to_quick_pulse_data_points( # pylint: disable=too-many-nested-block elif isinstance(point, NumberDataPoint): value = point.value metric_point = MetricPoint( - name=_QUICKPULSE_METRIC_NAME_MAPPINGS[metric.name.lower()], - weight=1, - value=value + name=_QUICKPULSE_METRIC_NAME_MAPPINGS[metric.name.lower()], weight=1, value=value ) metric_points.append(metric_point) return [ @@ -66,6 +66,7 @@ def _metric_to_quick_pulse_data_points( # pylint: disable=too-many-nested-block ) ] + # mypy: disable-error-code="assignment,union-attr" def _get_span_document(span: ReadableSpan) -> Union[RemoteDependencyDocument, RequestDocument]: duration = 0 @@ -97,6 +98,7 @@ def _get_span_document(span: ReadableSpan) -> Union[RemoteDependencyDocument, Re ) return document + # mypy: disable-error-code="assignment" def _get_log_record_document(log_data: LogData) -> Union[ExceptionDocument, TraceDocument]: exc_type = log_data.log_record.attributes.get(SpanAttributes.EXCEPTION_TYPE) # type: ignore diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_storage.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_storage.py index 8919079ed437..a3db175439c2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_storage.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_storage.py @@ -38,9 +38,7 @@ def delete(self): def get(self): try: with open(self.fullpath, "r", encoding="utf-8") as file: - return tuple( - json.loads(line.strip()) for line in file.readlines() - ) + return tuple(json.loads(line.strip()) for line in file.readlines()) except Exception: pass # keep silent return None @@ -141,7 +139,7 @@ def gets(self): except Exception: pass # keep silent if path.endswith(".lock"): - if path[path.rindex("@") + 1: -5] > lease_deadline: + if path[path.rindex("@") + 1 : -5] > lease_deadline: continue # under lease new_path = path[: path.rindex("@")] try: @@ -182,9 +180,7 @@ def put(self, data, lease_period=None): self._path, "{}-{}.blob".format( _fmt(_now()), - "{:08x}".format( - random.getrandbits(32) - ), # thread-safe random + "{:08x}".format(random.getrandbits(32)), # thread-safe random ), ) ) @@ -214,9 +210,7 @@ def _check_storage_size(self): "Persistent storage max capacity has been " "reached. Currently at {}KB. Telemetry will be " "lost. Please consider increasing the value of " - "'storage_max_size' in exporter config.".format( - str(size / 1024) - ) + "'storage_max_size' in exporter config.".format(str(size / 1024)) ) return False return True diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_utils.py index 31918726f9e4..a0e2a7845401 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_utils.py @@ -35,33 +35,40 @@ # Workaround for missing version file try: from importlib.metadata import version + opentelemetry_version = version("opentelemetry-sdk") except ImportError: # Temporary workaround for str: value, seconds = divmod(value, 60) value, minutes = divmod(value, 60) days, hours = divmod(value, 24) - return "{:d}.{:02d}:{:02d}:{:02d}.{:03d}".format( - days, hours, minutes, seconds, milliseconds - ) + return "{:d}.{:02d}:{:02d}:{:02d}.{:03d}".format(days, hours, minutes, seconds, milliseconds) # Replicate .netDateTime.Ticks(), which is the UTC time, expressed as the number @@ -144,11 +150,9 @@ def _ticks_since_dot_net_epoch(): # Since time.time() is the elapsed time since UTC January 1, 1970, we have # to shift this start time, and then multiply by 10^7 to get the number of # 100-nanosecond intervals - shift_time = int( - ( - datetime.datetime(1970, 1, 1, 0, 0, 0) - - datetime.datetime(1, 1, 1, 0, 0, 0)).total_seconds() - ) * (10 ** 7) + shift_time = int((datetime.datetime(1970, 1, 1, 0, 0, 0) - datetime.datetime(1, 1, 1, 0, 0, 0)).total_seconds()) * ( + 10**7 + ) # Add shift time to 100-ns intervals since time.time() return int(time.time() * (10**7)) + shift_time @@ -156,6 +160,7 @@ def _ticks_since_dot_net_epoch(): _INSTRUMENTATIONS_BIT_MASK = 0 _INSTRUMENTATIONS_BIT_MASK_LOCK = threading.Lock() + def get_instrumentations(): return _INSTRUMENTATIONS_BIT_MASK @@ -191,10 +196,10 @@ class PeriodicTask(threading.Thread): """ def __init__(self, interval: int, function: Callable, *args: Any, **kwargs: Any): - super().__init__(name=kwargs.pop('name', None)) + super().__init__(name=kwargs.pop("name", None)) self.interval = interval self.function = function - self.args = args or [] # type: ignore + self.args = args or [] # type: ignore self.kwargs = kwargs or {} self.finished = threading.Event() @@ -209,14 +214,16 @@ def run(self): def cancel(self): self.finished.set() + def _create_telemetry_item(timestamp: int) -> TelemetryItem: return TelemetryItem( name="", instrumentation_key="", - tags=dict(azure_monitor_context), # type: ignore - time=ns_to_iso_str(timestamp), # type: ignore + tags=dict(azure_monitor_context), # type: ignore + time=ns_to_iso_str(timestamp), # type: ignore ) + def _populate_part_a_fields(resource: Resource): tags = {} if resource and resource.attributes: @@ -229,26 +236,26 @@ def _populate_part_a_fields(resource: Resource): app_version = resource.attributes.get(ResourceAttributes.SERVICE_VERSION) if service_name: if service_namespace: - tags[ContextTagKeys.AI_CLOUD_ROLE] = str(service_namespace) + \ - "." + str(service_name) + tags[ContextTagKeys.AI_CLOUD_ROLE] = str(service_namespace) + "." + str(service_name) else: - tags[ContextTagKeys.AI_CLOUD_ROLE] = service_name # type: ignore + tags[ContextTagKeys.AI_CLOUD_ROLE] = service_name # type: ignore if service_instance_id: - tags[ContextTagKeys.AI_CLOUD_ROLE_INSTANCE] = service_instance_id # type: ignore + tags[ContextTagKeys.AI_CLOUD_ROLE_INSTANCE] = service_instance_id # type: ignore else: tags[ContextTagKeys.AI_CLOUD_ROLE_INSTANCE] = platform.node() # hostname default tags[ContextTagKeys.AI_INTERNAL_NODE_NAME] = tags[ContextTagKeys.AI_CLOUD_ROLE_INSTANCE] if device_id: - tags[ContextTagKeys.AI_DEVICE_ID] = device_id # type: ignore + tags[ContextTagKeys.AI_DEVICE_ID] = device_id # type: ignore if device_model: - tags[ContextTagKeys.AI_DEVICE_MODEL] = device_model # type: ignore + tags[ContextTagKeys.AI_DEVICE_MODEL] = device_model # type: ignore if device_make: - tags[ContextTagKeys.AI_DEVICE_OEM_NAME] = device_make # type: ignore + tags[ContextTagKeys.AI_DEVICE_OEM_NAME] = device_make # type: ignore if app_version: - tags[ContextTagKeys.AI_APPLICATION_VER] = app_version # type: ignore + tags[ContextTagKeys.AI_APPLICATION_VER] = app_version # type: ignore return tags + # pylint: disable=W0622 def _filter_custom_properties(properties: Attributes, filter=None) -> Dict[str, str]: truncated_properties: Dict[str, str] = {} @@ -269,19 +276,18 @@ def _filter_custom_properties(properties: Attributes, filter=None) -> Dict[str, def _get_auth_policy(credential, default_auth_policy): if credential: - if hasattr(credential, 'get_token'): + if hasattr(credential, "get_token"): return BearerTokenCredentialPolicy( credential, _APPLICATION_INSIGHTS_RESOURCE_SCOPE, ) - raise ValueError( - 'Must pass in valid TokenCredential.' - ) + raise ValueError("Must pass in valid TokenCredential.") return default_auth_policy class Singleton(type): _instance = None + def __call__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__call__(*args, **kwargs) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/_base.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/_base.py index 9072832817a2..3195116e0cc6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/_base.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/_base.py @@ -59,6 +59,7 @@ _TEMPDIR_PREFIX = "opentelemetry-python-" _SERVICE_API_LATEST = "2020-09-15_Preview" + class ExportResult(Enum): SUCCESS = 0 FAILED_RETRYABLE = 1 @@ -81,29 +82,39 @@ def __init__(self, **kwargs: Any) -> None: :keyword str storage_directory: Storage path in which to store retry files. Defaults to `/opentelemetry-python-`. :rtype: None """ - parsed_connection_string = ConnectionStringParser(kwargs.get('connection_string')) + parsed_connection_string = ConnectionStringParser(kwargs.get("connection_string")) - self._api_version = kwargs.get('api_version') or _SERVICE_API_LATEST - self._credential = kwargs.get('credential') + self._api_version = kwargs.get("api_version") or _SERVICE_API_LATEST + self._credential = kwargs.get("credential") self._consecutive_redirects = 0 # To prevent circular redirects - self._disable_offline_storage = kwargs.get('disable_offline_storage', False) + self._disable_offline_storage = kwargs.get("disable_offline_storage", False) self._endpoint = parsed_connection_string.endpoint self._instrumentation_key = parsed_connection_string.instrumentation_key - self._storage_maintenance_period = kwargs.get('storage_maintenance_period', 60) # Maintenance interval in seconds. - self._storage_max_size = kwargs.get('storage_max_size', 50 * 1024 * 1024) # Maximum size in bytes (default 50MiB) - self._storage_min_retry_interval = kwargs.get('storage_min_retry_interval', 60) # minimum retry interval in seconds + self._storage_maintenance_period = kwargs.get( + "storage_maintenance_period", 60 + ) # Maintenance interval in seconds. + self._storage_max_size = kwargs.get( + "storage_max_size", 50 * 1024 * 1024 + ) # Maximum size in bytes (default 50MiB) + self._storage_min_retry_interval = kwargs.get( + "storage_min_retry_interval", 60 + ) # minimum retry interval in seconds temp_suffix = self._instrumentation_key or "" - if 'storage_directory' in kwargs: - self._storage_directory = kwargs.get('storage_directory') + if "storage_directory" in kwargs: + self._storage_directory = kwargs.get("storage_directory") elif not self._disable_offline_storage: self._storage_directory = os.path.join( tempfile.gettempdir(), _AZURE_TEMPDIR_PREFIX, _TEMPDIR_PREFIX + temp_suffix ) else: self._storage_directory = None - self._storage_retention_period = kwargs.get('storage_retention_period', 48 * 60 * 60) # Retention period in seconds (default 48 hrs) - self._timeout = kwargs.get('timeout', 10.0) # networking timeout in seconds - self._distro_version = kwargs.get(_AZURE_MONITOR_DISTRO_VERSION_ARG, '') # If set, indicates the exporter is instantiated via Azure monitor OpenTelemetry distro. Versions corresponds to distro version. + self._storage_retention_period = kwargs.get( + "storage_retention_period", 48 * 60 * 60 + ) # Retention period in seconds (default 48 hrs) + self._timeout = kwargs.get("timeout", 10.0) # networking timeout in seconds + self._distro_version = kwargs.get( + _AZURE_MONITOR_DISTRO_VERSION_ARG, "" + ) # If set, indicates the exporter is instantiated via Azure monitor OpenTelemetry distro. Versions corresponds to distro version. config = AzureMonitorClientConfiguration(self._endpoint, **kwargs) policies = [ @@ -120,11 +131,12 @@ def __init__(self, **kwargs: Any) -> None: config.logging_policy, # Explicitly disabling to avoid infinite loop of Span creation when data is exported # DistributedTracingPolicy(**kwargs), - config.http_logging_policy or HttpLoggingPolicy(**kwargs) + config.http_logging_policy or HttpLoggingPolicy(**kwargs), ] self.client = AzureMonitorClient( - host=self._endpoint, connection_timeout=self._timeout, policies=policies, **kwargs) + host=self._endpoint, connection_timeout=self._timeout, policies=policies, **kwargs + ) self.storage = None if not self._disable_offline_storage: self.storage = LocalFileStorage( @@ -136,11 +148,12 @@ def __init__(self, **kwargs: Any) -> None: lease_period=self._storage_min_retry_interval, ) # specifies whether current exporter is used for collection of instrumentation metrics - self._instrumentation_collection = kwargs.get('instrumentation_collection', False) + self._instrumentation_collection = kwargs.get("instrumentation_collection", False) # statsbeat initialization if self._should_collect_stats(): # Import here to avoid circular dependencies from azure.monitor.opentelemetry.exporter.statsbeat._statsbeat import collect_statsbeat_metrics + collect_statsbeat_metrics(self) def _transmit_from_storage(self) -> None: @@ -192,8 +205,11 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: if not track_response.errors: # 200 self._consecutive_redirects = 0 if not self._is_stats_exporter(): - logger.info("Transmission succeeded: Item received: %s. Items accepted: %s", - track_response.items_received, track_response.items_accepted) + logger.info( + "Transmission succeeded: Item received: %s. Items accepted: %s", + track_response.items_received, + track_response.items_accepted, + ) if self._should_collect_stats(): _update_requests_map(_REQ_SUCCESS_NAME[1], 1) reach_ingestion = True @@ -203,9 +219,7 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: resend_envelopes = [] for error in track_response.errors: if _is_retryable_code(error.status_code): - resend_envelopes.append( - envelopes[error.index] # type: ignore - ) + resend_envelopes.append(envelopes[error.index]) # type: ignore if self._should_collect_stats(): _update_requests_map(_REQ_RETRY_NAME[1], value=error.status_code) else: @@ -217,8 +231,7 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: envelopes[error.index] if error.index is not None else "", ) if self.storage and resend_envelopes: - envelopes_to_store = [x.as_dict() - for x in resend_envelopes] + envelopes_to_store = [x.as_dict() for x in resend_envelopes] self.storage.put(envelopes_to_store, 0) self._consecutive_redirects = 0 # Mark as not retryable because we already write to storage here @@ -238,10 +251,10 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: elif _is_redirect_code(response_error.status_code): self._consecutive_redirects = self._consecutive_redirects + 1 # pylint: disable=W0212 - if self._consecutive_redirects < self.client._config.redirect_policy.max_redirects: # type: ignore - if response_error.response and response_error.response.headers: # type: ignore + if self._consecutive_redirects < self.client._config.redirect_policy.max_redirects: # type: ignore + if response_error.response and response_error.response.headers: # type: ignore redirect_has_headers = True - location = response_error.response.headers.get("location") # type: ignore + location = response_error.response.headers.get("location") # type: ignore url = urlparse(location) else: redirect_has_headers = False @@ -259,7 +272,7 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: else: if not self._is_stats_exporter(): logger.error( - "Error sending telemetry because of circular redirects. " \ + "Error sending telemetry because of circular redirects. " "Please check the integrity of your connection string." ) # If redirect but did not return, exception occurred @@ -274,40 +287,39 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: _update_requests_map(_REQ_FAILURE_NAME[1], value=response_error.status_code) if not self._is_stats_exporter(): logger.error( - 'Non-retryable server side error: %s.', + "Non-retryable server side error: %s.", response_error.message, ) if _is_invalid_code(response_error.status_code): # Shutdown statsbeat on invalid code from customer endpoint # Import here to avoid circular dependencies - from azure.monitor.opentelemetry.exporter.statsbeat._statsbeat import shutdown_statsbeat_metrics + from azure.monitor.opentelemetry.exporter.statsbeat._statsbeat import ( + shutdown_statsbeat_metrics, + ) + shutdown_statsbeat_metrics() result = ExportResult.FAILED_NOT_RETRYABLE except ServiceRequestError as request_error: # Errors when we're fairly sure that the server did not receive the # request, so it should be safe to retry. # ServiceRequestError is raised by azure.core for these cases - logger.warning( - "Retrying due to server request error: %s.", request_error.message - ) + logger.warning("Retrying due to server request error: %s.", request_error.message) if self._should_collect_stats(): exc_type = request_error.exc_type if exc_type is None or exc_type is type(None): - exc_type = request_error.__class__.__name__ # type: ignore + exc_type = request_error.__class__.__name__ # type: ignore _update_requests_map(_REQ_EXCEPTION_NAME[1], value=exc_type) result = ExportResult.FAILED_RETRYABLE except Exception as ex: - logger.error( - "Envelopes could not be exported and are not retryable: %s.", ex - ) + logger.error("Envelopes could not be exported and are not retryable: %s.", ex) if self._should_collect_stats(): _update_requests_map(_REQ_EXCEPTION_NAME[1], value=ex.__class__.__name__) result = ExportResult.FAILED_NOT_RETRYABLE finally: if self._should_collect_stats(): end_time = time.time() - _update_requests_map('count', 1) - _update_requests_map(_REQ_DURATION_NAME[1], value=end_time-start_time) + _update_requests_map("count", 1) + _update_requests_map(_REQ_DURATION_NAME[1], value=end_time - start_time) if self._is_statsbeat_initializing_state(): # Update statsbeat initial success state if reached ingestion if reach_ingestion: @@ -317,7 +329,10 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: # has been reached during attempting statsbeat initialization if increment_and_check_statsbeat_failure_count(): # Import here to avoid circular dependencies - from azure.monitor.opentelemetry.exporter.statsbeat._statsbeat import shutdown_statsbeat_metrics + from azure.monitor.opentelemetry.exporter.statsbeat._statsbeat import ( + shutdown_statsbeat_metrics, + ) + shutdown_statsbeat_metrics() # pylint: disable=lost-exception return ExportResult.FAILED_NOT_RETRYABLE # pylint: disable=W0012,W0134 @@ -330,16 +345,16 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: # check to see whether its the case of stats collection def _should_collect_stats(self): - return is_statsbeat_enabled() and \ - not get_statsbeat_shutdown() and \ - not self._is_stats_exporter() and \ - not self._instrumentation_collection + return ( + is_statsbeat_enabled() + and not get_statsbeat_shutdown() + and not self._is_stats_exporter() + and not self._instrumentation_collection + ) # check to see if statsbeat is in "attempting to be initialized" state def _is_statsbeat_initializing_state(self): - return self._is_stats_exporter() and \ - not get_statsbeat_shutdown() and \ - not get_statsbeat_initial_success() + return self._is_stats_exporter() and not get_statsbeat_shutdown() and not get_statsbeat_initial_success() def _is_stats_exporter(self): return self.__class__.__name__ == "_StatsBeatExporter" @@ -417,6 +432,6 @@ def _format_storage_telemetry_item(item: TelemetryItem) -> TelemetryItem: base_type = _MONITOR_DOMAIN_MAPPING.get(item.data.base_type) # Apply deserialization of additional_properties and store that as base_data if base_type: - item.data.base_data = base_type.from_dict(item.data.base_data.additional_properties) # type: ignore - item.data.base_data.additional_properties = None # type: ignore + item.data.base_data = base_type.from_dict(item.data.base_data.additional_properties) # type: ignore + item.data.base_data.additional_properties = None # type: ignore return item diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/logs/_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/logs/_exporter.py index 0632a7265e82..0b701bfdbafd 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/logs/_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/logs/_exporter.py @@ -1,5 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +import json import logging from typing import Optional, Sequence, Any @@ -52,9 +53,7 @@ class AzureMonitorLogExporter(BaseExporter, LogExporter): """Azure Monitor Log exporter for OpenTelemetry.""" - def export( - self, batch: Sequence[LogData], **kwargs: Any # pylint: disable=unused-argument - ) -> LogExportResult: + def export(self, batch: Sequence[LogData], **kwargs: Any) -> LogExportResult: # pylint: disable=unused-argument """Export log data. :param batch: OpenTelemetry LogData(s) to export. @@ -86,9 +85,7 @@ def _log_to_envelope(self, log_data: LogData) -> TelemetryItem: # pylint: disable=docstring-keyword-should-match-keyword-only @classmethod - def from_connection_string( - cls, conn_str: str, **kwargs: Any - ) -> "AzureMonitorLogExporter": + def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "AzureMonitorLogExporter": """ Create an AzureMonitorLogExporter from a connection string. This is the recommended way of instantiation if a connection string is passed in @@ -110,24 +107,24 @@ def _log_data_is_event(log_data: LogData): log_record = log_data.log_record is_event = False if log_record.attributes: - is_event = log_record.attributes.get(_APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE, False) # type: ignore + is_event = log_record.attributes.get(_APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE, False) # type: ignore return is_event is True + # pylint: disable=protected-access def _convert_log_to_envelope(log_data: LogData) -> TelemetryItem: log_record = log_data.log_record time_stamp = log_record.timestamp if log_record.timestamp is not None else log_record.observed_timestamp envelope = _utils._create_telemetry_item(time_stamp) - envelope.tags.update(_utils._populate_part_a_fields(log_record.resource)) # type: ignore - envelope.tags[ContextTagKeys.AI_OPERATION_ID] = "{:032x}".format( # type: ignore + envelope.tags.update(_utils._populate_part_a_fields(log_record.resource)) # type: ignore + envelope.tags[ContextTagKeys.AI_OPERATION_ID] = "{:032x}".format( # type: ignore log_record.trace_id or _DEFAULT_TRACE_ID ) - envelope.tags[ContextTagKeys.AI_OPERATION_PARENT_ID] = "{:016x}".format( # type: ignore + envelope.tags[ContextTagKeys.AI_OPERATION_PARENT_ID] = "{:016x}".format( # type: ignore log_record.span_id or _DEFAULT_SPAN_ID ) properties = _utils._filter_custom_properties( - log_record.attributes, - lambda key, val: not _is_ignored_attribute(key) + log_record.attributes, lambda key, val: not _is_ignored_attribute(key) ) exc_type = exc_message = stack_trace = None if log_record.attributes: @@ -139,12 +136,10 @@ def _convert_log_to_envelope(log_data: LogData) -> TelemetryItem: # Event telemetry if _log_data_is_event(log_data): - if not log_record.body: - log_record.body = "n/a" _set_statsbeat_custom_events_feature() - envelope.name = 'Microsoft.ApplicationInsights.Event' + envelope.name = "Microsoft.ApplicationInsights.Event" data = TelemetryEventData( - name=str(log_record.body)[:32768], + name=_map_body_to_message(log_record.body), properties=properties, ) envelope.data = MonitorBase(base_data=data, base_type="EventData") @@ -156,18 +151,18 @@ def _convert_log_to_envelope(log_data: LogData) -> TelemetryItem: exc_type = "Exception" # Log body takes priority for message if log_record.body: - message = str(log_record.body) + message = _map_body_to_message(log_record.body) elif exc_message: - message = exc_message # type: ignore + message = exc_message # type: ignore else: message = "Exception" exc_details = TelemetryExceptionDetails( - type_name=str(exc_type)[:1024], # type: ignore + type_name=str(exc_type)[:1024], # type: ignore message=str(message)[:32768], has_full_stack=has_full_stack, stack=str(stack_trace)[:32768], ) - data = TelemetryExceptionData( # type: ignore + data = TelemetryExceptionData( # type: ignore severity_level=severity_level, properties=properties, exceptions=[exc_details], @@ -175,13 +170,11 @@ def _convert_log_to_envelope(log_data: LogData) -> TelemetryItem: # pylint: disable=line-too-long envelope.data = MonitorBase(base_data=data, base_type="ExceptionData") else: # Message telemetry - if not log_record.body: - log_record.body = "n/a" envelope.name = _MESSAGE_ENVELOPE_NAME # pylint: disable=line-too-long # Severity number: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#field-severitynumber - data = MessageData( # type: ignore - message=str(log_record.body)[:32768], + data = MessageData( # type: ignore + message=_map_body_to_message(log_record.body), severity_level=severity_level, properties=properties, ) @@ -205,6 +198,22 @@ def _get_severity_level(severity_number: Optional[SeverityNumber]): return int((severity_number.value - 1) / 4 - 1) +def _map_body_to_message(log_body: Any) -> str: + if not log_body: + return "" + + if isinstance(log_body, str): + return log_body[:32768] + + if isinstance(log_body, Exception): + return str(log_body)[:32768] + + try: + return json.dumps(log_body)[:32768] + except: # pylint: disable=bare-except + return str(log_body)[:32768] + + def _is_ignored_attribute(key: str) -> bool: return key in _IGNORED_ATTRS @@ -219,6 +228,7 @@ def _is_ignored_attribute(key: str) -> bool: ) ) + def _set_statsbeat_custom_events_feature(): if is_statsbeat_enabled() and not get_statsbeat_shutdown() and not get_statsbeat_custom_events_feature_set(): set_statsbeat_custom_events_feature_set() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/metrics/_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/metrics/_exporter.py index 8d22e8455006..9264b4d19923 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/metrics/_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/metrics/_exporter.py @@ -65,8 +65,8 @@ def __init__(self, **kwargs: Any) -> None: BaseExporter.__init__(self, **kwargs) MetricExporter.__init__( self, - preferred_temporality=APPLICATION_INSIGHTS_METRIC_TEMPORALITIES, # type: ignore - preferred_aggregation=kwargs.get("preferred_aggregation"), # type: ignore + preferred_temporality=APPLICATION_INSIGHTS_METRIC_TEMPORALITIES, # type: ignore + preferred_aggregation=kwargs.get("preferred_aggregation"), # type: ignore ) # pylint: disable=R1702 @@ -141,16 +141,14 @@ def _point_to_envelope( ) -> Optional[TelemetryItem]: envelope = _convert_point_to_envelope(point, name, resource, scope) if name in _AUTOCOLLECTED_INSTRUMENT_NAMES: - envelope = _handle_std_metric_envelope(envelope, name, point.attributes) # type: ignore + envelope = _handle_std_metric_envelope(envelope, name, point.attributes) # type: ignore if envelope is not None: envelope.instrumentation_key = self._instrumentation_key return envelope # pylint: disable=docstring-keyword-should-match-keyword-only @classmethod - def from_connection_string( - cls, conn_str: str, **kwargs: Any - ) -> "AzureMonitorMetricExporter": + def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "AzureMonitorMetricExporter": """ Create an AzureMonitorMetricExporter from a connection string. This is the recommended way of instantiation if a connection string is passed in @@ -170,14 +168,11 @@ def from_connection_string( # pylint: disable=protected-access def _convert_point_to_envelope( - point: DataPointT, - name: str, - resource: Optional[Resource] = None, - scope: Optional[InstrumentationScope] = None + point: DataPointT, name: str, resource: Optional[Resource] = None, scope: Optional[InstrumentationScope] = None ) -> TelemetryItem: envelope = _utils._create_telemetry_item(point.time_unix_nano) envelope.name = _METRIC_ENVELOPE_NAME - envelope.tags.update(_utils._populate_part_a_fields(resource)) # type: ignore + envelope.tags.update(_utils._populate_part_a_fields(resource)) # type: ignore namespace = None if scope is not None and _is_metric_namespace_opted_in(): namespace = str(scope.name)[:256] @@ -231,7 +226,7 @@ def _handle_std_metric_envelope( status_code = attributes.get("http.status_code") if status_code: try: - status_code = int(status_code) # type: ignore + status_code = int(status_code) # type: ignore except ValueError: status_code = 0 else: @@ -240,34 +235,33 @@ def _handle_std_metric_envelope( properties["_MS.MetricId"] = "dependencies/duration" properties["_MS.IsAutocollected"] = "True" properties["Dependency.Type"] = "http" - properties["Dependency.Success"] = str(_is_status_code_success(status_code)) # type: ignore + properties["Dependency.Success"] = str(_is_status_code_success(status_code)) # type: ignore target = None if "peer.service" in attributes: - target = attributes["peer.service"] # type: ignore + target = attributes["peer.service"] # type: ignore elif "net.peer.name" in attributes: - if attributes["net.peer.name"] is None: # type: ignore + if attributes["net.peer.name"] is None: # type: ignore target = None - elif "net.host.port" in attributes and \ - attributes["net.host.port"] is not None: # type: ignore + elif "net.host.port" in attributes and attributes["net.host.port"] is not None: # type: ignore target = "{}:{}".format( - attributes["net.peer.name"], # type: ignore - attributes["net.host.port"], # type: ignore + attributes["net.peer.name"], # type: ignore + attributes["net.host.port"], # type: ignore ) else: - target = attributes["net.peer.name"] # type: ignore - properties["dependency/target"] = target # type: ignore + target = attributes["net.peer.name"] # type: ignore + properties["dependency/target"] = target # type: ignore properties["dependency/resultCode"] = str(status_code) # TODO: operation/synthetic - properties["cloud/roleInstance"] = tags["ai.cloud.roleInstance"] # type: ignore - properties["cloud/roleName"] = tags["ai.cloud.role"] # type: ignore + properties["cloud/roleInstance"] = tags["ai.cloud.roleInstance"] # type: ignore + properties["cloud/roleName"] = tags["ai.cloud.role"] # type: ignore elif name == "http.server.duration": properties["_MS.MetricId"] = "requests/duration" properties["_MS.IsAutocollected"] = "True" properties["request/resultCode"] = str(status_code) # TODO: operation/synthetic - properties["cloud/roleInstance"] = tags["ai.cloud.roleInstance"] # type: ignore - properties["cloud/roleName"] = tags["ai.cloud.role"] # type: ignore - properties["Request.Success"] = str(_is_status_code_success(status_code)) # type: ignore + properties["cloud/roleInstance"] = tags["ai.cloud.roleInstance"] # type: ignore + properties["cloud/roleName"] = tags["ai.cloud.role"] # type: ignore + properties["Request.Success"] = str(_is_status_code_success(status_code)) # type: ignore else: # Any other autocollected metrics are not supported yet for standard metrics # We ignore these envelopes in these cases @@ -275,7 +269,7 @@ def _handle_std_metric_envelope( # TODO: rpc, database, messaging - envelope.data.base_data.properties = properties # type: ignore + envelope.data.base_data.properties = properties # type: ignore return envelope @@ -294,6 +288,7 @@ def _is_status_code_success(status_code: Optional[str]) -> bool: def _is_metric_namespace_opted_in() -> bool: return os.environ.get(_APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN, "False").lower() == "true" + def _get_metric_export_result(result: ExportResult) -> MetricExportResult: if result == ExportResult.SUCCESS: return MetricExportResult.SUCCESS diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_exporter.py index a99d9cc4e6f6..89df5220caa6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_exporter.py @@ -8,6 +8,7 @@ from urllib.parse import urlparse from opentelemetry.semconv.trace import DbSystemValues, SpanAttributes +from opentelemetry.semconv._incubating.attributes import gen_ai_attributes from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import ReadableSpan from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult @@ -36,7 +37,7 @@ RequestData, TelemetryExceptionData, TelemetryExceptionDetails, - TelemetryItem + TelemetryItem, ) from azure.monitor.opentelemetry.exporter.export._base import ( BaseExporter, @@ -76,7 +77,9 @@ def __init__(self, **kwargs: Any): self._tracer_provider = kwargs.pop("tracer_provider", None) super().__init__(**kwargs) - def export(self, spans: Sequence[ReadableSpan], **kwargs: Any) -> SpanExportResult: # pylint: disable=unused-argument + def export( + self, spans: Sequence[ReadableSpan], **kwargs: Any # pylint: disable=unused-argument + ) -> SpanExportResult: """Export span data. :param spans: Open Telemetry Spans to export. @@ -89,7 +92,7 @@ def export(self, spans: Sequence[ReadableSpan], **kwargs: Any) -> SpanExportResu resource = None try: tracer_provider = self._tracer_provider or get_tracer_provider() - resource = tracer_provider.resource # type: ignore + resource = tracer_provider.resource # type: ignore envelopes.append(self._get_otel_resource_envelope(resource)) except AttributeError as e: _logger.exception("Failed to derive Resource from Tracer Provider: %s", e) @@ -119,7 +122,7 @@ def _get_otel_resource_envelope(self, resource: Resource) -> TelemetryItem: attributes = resource.attributes envelope = _utils._create_telemetry_item(time_ns()) envelope.name = _METRIC_ENVELOPE_NAME - envelope.tags.update(_utils._populate_part_a_fields(resource)) # pylint: disable=W0212 + envelope.tags.update(_utils._populate_part_a_fields(resource)) # pylint: disable=W0212 envelope.instrumentation_key = self._instrumentation_key data_point = MetricDataPoint( name=str("_OTELRESOURCE_")[:1024], @@ -171,6 +174,7 @@ def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "AzureMonitorTr """ return cls(connection_string=conn_str, **kwargs) + # pylint: disable=too-many-statements # pylint: disable=too-many-branches # pylint: disable=too-many-locals @@ -191,9 +195,7 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: if SpanAttributes.ENDUSER_ID in span.attributes: envelope.tags[ContextTagKeys.AI_USER_ID] = span.attributes[SpanAttributes.ENDUSER_ID] if span.parent and span.parent.span_id: - envelope.tags[ContextTagKeys.AI_OPERATION_PARENT_ID] = "{:016x}".format( - span.parent.span_id - ) + envelope.tags[ContextTagKeys.AI_OPERATION_PARENT_ID] = "{:016x}".format(span.parent.span_id) # pylint: disable=too-many-nested-blocks if span.kind in (SpanKind.CONSUMER, SpanKind.SERVER): envelope.name = _REQUEST_ENVELOPE_NAME @@ -217,7 +219,7 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: total = 0 for link in span.links: attributes = link.attributes - enqueued_time = attributes.get("enqueuedTime") + enqueued_time = attributes.get("enqueuedTime") if isinstance(enqueued_time, int): difference = (start_time / 1000000) - enqueued_time total += difference @@ -283,7 +285,7 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: status_code = span.attributes.get(SpanAttributes.HTTP_STATUS_CODE) if status_code: try: - status_code = int(status_code) # type: ignore + status_code = int(status_code) # type: ignore except ValueError: status_code = 0 else: @@ -306,7 +308,7 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: span.attributes.get(SpanAttributes.MESSAGING_DESTINATION), ) else: - data.source = span.attributes.get(SpanAttributes.MESSAGING_DESTINATION, '') + data.source = span.attributes.get(SpanAttributes.MESSAGING_DESTINATION, "") # Apply truncation # See https://github.com/MohanGsk/ApplicationInsights-Home/tree/master/EndpointSpecs/Schemas/Bond if envelope.tags.get(ContextTagKeys.AI_OPERATION_NAME): @@ -323,17 +325,15 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: time = 0 if span.end_time and span.start_time: time = span.end_time - span.start_time - data = RemoteDependencyData( # type: ignore + data = RemoteDependencyData( # type: ignore name=span.name, id="{:016x}".format(span.context.span_id), result_code="0", duration=_utils.ns_to_duration(time), - success=span.status.is_ok, # Success depends only on span status + success=span.status.is_ok, # Success depends only on span status properties={}, ) - envelope.data = MonitorBase( - base_data=data, base_type="RemoteDependencyData" - ) + envelope.data = MonitorBase(base_data=data, base_type="RemoteDependencyData") target = None if SpanAttributes.PEER_SERVICE in span.attributes: target = span.attributes[SpanAttributes.PEER_SERVICE] @@ -348,8 +348,8 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: # This logic assumes default ports never conflict across dependency types # type: ignore if port != trace_utils._get_default_port_http( - str(span.attributes.get(SpanAttributes.HTTP_SCHEME))) and \ - port != trace_utils._get_default_port_db(str(span.attributes.get(SpanAttributes.DB_SYSTEM))): + str(span.attributes.get(SpanAttributes.HTTP_SCHEME)) + ) and port != trace_utils._get_default_port_db(str(span.attributes.get(SpanAttributes.DB_SYSTEM))): target = "{}:{}".format(target, port) if span.kind is SpanKind.CLIENT: if _AZURE_SDK_NAMESPACE_NAME in span.attributes: # Azure specific resources @@ -382,7 +382,7 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: status_code = span.attributes.get(SpanAttributes.HTTP_STATUS_CODE) if status_code: try: - status_code = int(status_code) # type: ignore + status_code = int(status_code) # type: ignore except ValueError: status_code = 0 else: @@ -425,6 +425,8 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: target, # type: ignore span.attributes, ) + elif gen_ai_attributes.GEN_AI_SYSTEM in span.attributes: # GenAI + data.type = span.attributes[gen_ai_attributes.GEN_AI_SYSTEM] else: data.type = "N/A" elif span.kind is SpanKind.PRODUCER: # Messaging @@ -463,14 +465,15 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: envelope.sample_rate = span.attributes[_SAMPLE_RATE_KEY] data.properties = _utils._filter_custom_properties( - span.attributes, - lambda key, val: not _is_standard_attribute(key) + span.attributes, lambda key, val: not _is_standard_attribute(key) ) # Standard metrics special properties # Only add the property if span was generated from instrumentation that supports metrics collection - if span.instrumentation_scope is not None and \ - span.instrumentation_scope.name in _INSTRUMENTATION_SUPPORTING_METRICS_LIST: + if ( + span.instrumentation_scope is not None + and span.instrumentation_scope.name in _INSTRUMENTATION_SUPPORTING_METRICS_LIST + ): data.properties["_MS.ProcessedByMetricExtractors"] = "True" if span.links: @@ -486,6 +489,7 @@ def _convert_span_to_envelope(span: ReadableSpan) -> TelemetryItem: data.properties["_MS.links"] = json.dumps(links) return envelope + # pylint: disable=protected-access def _convert_span_events_to_envelopes(span: ReadableSpan) -> Sequence[TelemetryItem]: envelopes = [] @@ -494,17 +498,14 @@ def _convert_span_events_to_envelopes(span: ReadableSpan) -> Sequence[TelemetryI envelope.tags.update(_utils._populate_part_a_fields(span.resource)) envelope.tags[ContextTagKeys.AI_OPERATION_ID] = "{:032x}".format(span.context.trace_id) if span.context and span.context.span_id: - envelope.tags[ContextTagKeys.AI_OPERATION_PARENT_ID] = "{:016x}".format( - span.context.span_id - ) + envelope.tags[ContextTagKeys.AI_OPERATION_PARENT_ID] = "{:016x}".format(span.context.span_id) # sampleRate if span.attributes and _SAMPLE_RATE_KEY in span.attributes: envelope.sample_rate = span.attributes[_SAMPLE_RATE_KEY] properties = _utils._filter_custom_properties( - event.attributes, - lambda key, val: not _is_standard_attribute(key) + event.attributes, lambda key, val: not _is_standard_attribute(key) ) if event.name == "exception": envelope.name = _EXCEPTION_ENVELOPE_NAME @@ -529,14 +530,14 @@ def _convert_span_events_to_envelopes(span: ReadableSpan) -> Sequence[TelemetryI exceptions=[exc_details], ) # pylint: disable=line-too-long - envelope.data = MonitorBase(base_data=data, base_type='ExceptionData') + envelope.data = MonitorBase(base_data=data, base_type="ExceptionData") else: envelope.name = _MESSAGE_ENVELOPE_NAME - data = MessageData( # type: ignore + data = MessageData( # type: ignore message=str(event.name)[:32768], properties=properties, ) - envelope.data = MonitorBase(base_data=data, base_type='MessageData') + envelope.data = MonitorBase(base_data=data, base_type="MessageData") envelopes.append(envelope) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_sampling.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_sampling.py index e3378780b578..bf997df8eb11 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_sampling.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_sampling.py @@ -4,6 +4,7 @@ # pylint:disable=no-name-in-module from fixedint import Int32 + # pylint:disable=W0611 from opentelemetry.context import Context from opentelemetry.trace import Link, SpanKind, format_trace_id @@ -65,11 +66,11 @@ def should_sample( # Add sample rate as span attribute if attributes is None: attributes = {} - attributes[_SAMPLE_RATE_KEY] = self._sample_rate # type: ignore + attributes[_SAMPLE_RATE_KEY] = self._sample_rate # type: ignore return SamplingResult( decision, attributes, - _get_parent_trace_state(parent_context), # type: ignore + _get_parent_trace_state(parent_context), # type: ignore ) def _get_DJB2_sample_score(self, trace_id_hex: str) -> float: @@ -86,7 +87,6 @@ def _get_DJB2_sample_score(self, trace_id_hex: str) -> float: # divide by _INTEGER_MAX for value between 0 and 1 for sampling score return float(hash_value) / _INTEGER_MAX - def get_description(self) -> str: return "ApplicationInsightsSampler{}".format(self._ratio) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_utils.py index 767a25838288..c0949bbbaf4a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/export/trace/_utils.py @@ -54,7 +54,7 @@ def _is_sql_db(db_system: str) -> bool: # spell-checker:ignore HSQLDB DbSystemValues.HSQLDB.value, DbSystemValues.H2.value, - ) + ) def _get_azure_sdk_target_source(attributes: Attributes) -> Optional[str]: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_exporter.py index e711731f9ca6..a449a5bae5ba 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_exporter.py @@ -18,7 +18,7 @@ def _point_to_envelope( point: DataPointT, name: str, resource: Optional[Resource] = None, - scope: Optional[InstrumentationScope] = None + scope: Optional[InstrumentationScope] = None, ) -> Optional[TelemetryItem]: # map statsbeat name from OpenTelemetry name name = _STATSBEAT_METRIC_NAME_MAPPINGS[name] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_state.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_state.py index 3530f71364fd..e555ba719a68 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_state.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_state.py @@ -19,6 +19,7 @@ _STATSBEAT_STATE_LOCK = threading.Lock() _STATSBEAT_FAILURE_COUNT_THRESHOLD = 3 + def is_statsbeat_enabled(): disabled = os.environ.get(_APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL) return disabled is None or disabled.lower() != "true" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_statsbeat.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_statsbeat.py index de75661d6ee5..e6dcee0c3aca 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_statsbeat.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_statsbeat.py @@ -22,6 +22,7 @@ _STATSBEAT_METRICS = None _STATSBEAT_LOCK = threading.Lock() + # pylint: disable=global-statement # pylint: disable=protected-access def collect_statsbeat_metrics(exporter) -> None: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_statsbeat_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_statsbeat_metrics.py index bdc332334830..0eabae80c359 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_statsbeat_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_statsbeat_metrics.py @@ -44,6 +44,8 @@ _AIMS_FORMAT = "format=json" _ENDPOINT_TYPES = ["breeze"] + + class _RP_Names(Enum): APP_SERVICE = "appsvc" FUNCTIONS = "functions" @@ -51,7 +53,8 @@ class _RP_Names(Enum): VM = "vm" UNKNOWN = "unknown" -_HOST_PATTERN = re.compile('^https?://(?:www\\.)?([^/.]+)') + +_HOST_PATTERN = re.compile("^https?://(?:www\\.)?([^/.]+)") class _FEATURE_TYPES: @@ -84,7 +87,7 @@ class _StatsbeatMetrics: "runtimeVersion": platform.python_version(), "os": platform.system(), "language": "python", - "version": VERSION + "version": VERSION, } _NETWORK_ATTRIBUTES: Dict[str, Any] = { @@ -151,7 +154,7 @@ def __init__( _ATTACH_METRIC_NAME[0], callbacks=[self._get_attach_metric], unit="", - description="Statsbeat metric tracking tracking rp information" + description="Statsbeat metric tracking tracking rp information", ) # Feature metrics - metrics related to features/instrumentations being used @@ -159,7 +162,7 @@ def __init__( _FEATURE_METRIC_NAME[0], callbacks=[self._get_feature_metric], unit="", - description="Statsbeat metric tracking tracking enabled features" + description="Statsbeat metric tracking tracking enabled features", ) # pylint: disable=unused-argument @@ -169,32 +172,27 @@ def _get_attach_metric(self, options: CallbackOptions) -> Iterable[Observation]: # Check if it is time to observe long interval metrics if not self._meets_long_interval_threshold(_ATTACH_METRIC_NAME[0]): return observations - rp = '' - rpId = '' + rp = "" + rpId = "" os_type = platform.system() # rp, rpId if _utils._is_on_app_service(): # Web apps rp = _RP_Names.APP_SERVICE.value - rpId = '{}/{}'.format( - os.environ.get(_WEBSITE_SITE_NAME), - os.environ.get(_WEBSITE_HOME_STAMPNAME, '') - ) + rpId = "{}/{}".format(os.environ.get(_WEBSITE_SITE_NAME), os.environ.get(_WEBSITE_HOME_STAMPNAME, "")) elif _utils._is_on_functions(): # Function apps rp = _RP_Names.FUNCTIONS.value - rpId = os.environ.get(_WEBSITE_HOSTNAME, '') + rpId = os.environ.get(_WEBSITE_HOSTNAME, "") elif _utils._is_on_aks(): # AKS rp = _RP_Names.AKS.value - rpId = os.environ.get(_AKS_ARM_NAMESPACE_ID, '') + rpId = os.environ.get(_AKS_ARM_NAMESPACE_ID, "") elif self._vm_retry and self._get_azure_compute_metadata(): # VM rp = _RP_Names.VM.value - rpId = '{}/{}'.format( - self._vm_data.get("vmId", ''), - self._vm_data.get("subscriptionId", '')) - os_type = self._vm_data.get("osType", '') + rpId = "{}/{}".format(self._vm_data.get("vmId", ""), self._vm_data.get("subscriptionId", "")) + os_type = self._vm_data.get("osType", "") else: # Not in any rp or VM metadata failed rp = _RP_Names.UNKNOWN.value @@ -203,16 +201,14 @@ def _get_attach_metric(self, options: CallbackOptions) -> Iterable[Observation]: _StatsbeatMetrics._COMMON_ATTRIBUTES["rp"] = rp _StatsbeatMetrics._COMMON_ATTRIBUTES["os"] = os_type or platform.system() attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) - attributes['rpId'] = rpId - observations.append(Observation(1, dict(attributes))) # type: ignore + attributes["rpId"] = rpId + observations.append(Observation(1, dict(attributes))) # type: ignore return observations def _get_azure_compute_metadata(self) -> bool: try: - request_url = "{0}?{1}&{2}".format( - _AIMS_URI, _AIMS_API_VERSION, _AIMS_FORMAT) - response = requests.get( - request_url, headers={"MetaData": "True"}, timeout=0.2) + request_url = "{0}?{1}&{2}".format(_AIMS_URI, _AIMS_API_VERSION, _AIMS_FORMAT) + response = requests.get(request_url, headers={"MetaData": "True"}, timeout=0.2) except (requests.exceptions.ConnectionError, requests.Timeout): # Not in VM self._vm_retry = False @@ -249,8 +245,8 @@ def _get_feature_metric(self, options: CallbackOptions) -> Iterable[Observation] # Don't send observation if no features enabled if self._feature is not _StatsbeatFeature.NONE: attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) - attributes.update(_StatsbeatMetrics._FEATURE_ATTRIBUTES) # type: ignore - observations.append(Observation(1, dict(attributes))) # type: ignore + attributes.update(_StatsbeatMetrics._FEATURE_ATTRIBUTES) # type: ignore + observations.append(Observation(1, dict(attributes))) # type: ignore # instrumentation metric # Don't send observation if no instrumentations enabled @@ -258,8 +254,8 @@ def _get_feature_metric(self, options: CallbackOptions) -> Iterable[Observation] if instrumentation_bits != 0: _StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES["feature"] = instrumentation_bits attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) - attributes.update(_StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES) # type: ignore - observations.append(Observation(1, dict(attributes))) # type: ignore + attributes.update(_StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES) # type: ignore + observations.append(Observation(1, dict(attributes))) # type: ignore return observations @@ -281,37 +277,37 @@ def init_non_initial_metrics(self): _REQ_SUCCESS_NAME[0], callbacks=[self._get_success_count], unit="count", - description="Statsbeat metric tracking request success count" + description="Statsbeat metric tracking request success count", ) self._failure_count = self._meter.create_observable_gauge( _REQ_FAILURE_NAME[0], callbacks=[self._get_failure_count], unit="count", - description="Statsbeat metric tracking request failure count" + description="Statsbeat metric tracking request failure count", ) self._retry_count = self._meter.create_observable_gauge( _REQ_RETRY_NAME[0], callbacks=[self._get_retry_count], unit="count", - description="Statsbeat metric tracking request retry count" + description="Statsbeat metric tracking request retry count", ) self._throttle_count = self._meter.create_observable_gauge( _REQ_THROTTLE_NAME[0], callbacks=[self._get_throttle_count], unit="count", - description="Statsbeat metric tracking request throttle count" + description="Statsbeat metric tracking request throttle count", ) self._exception_count = self._meter.create_observable_gauge( _REQ_EXCEPTION_NAME[0], callbacks=[self._get_exception_count], unit="count", - description="Statsbeat metric tracking request exception count" + description="Statsbeat metric tracking request exception count", ) self._average_duration = self._meter.create_observable_gauge( _REQ_DURATION_NAME[0], callbacks=[self._get_average_duration], unit="avg", - description="Statsbeat metric tracking average request duration" + description="Statsbeat metric tracking average request duration", ) # pylint: disable=unused-argument @@ -329,11 +325,9 @@ def _get_success_count(self, options: CallbackOptions) -> Iterable[Observation]: attributes["statusCode"] = 200 with _REQUESTS_MAP_LOCK: # only observe if value is not 0 - count = _REQUESTS_MAP.get(_REQ_SUCCESS_NAME[1], 0) # type: ignore + count = _REQUESTS_MAP.get(_REQ_SUCCESS_NAME[1], 0) # type: ignore if count != 0: - observations.append( - Observation(int(count), dict(attributes)) - ) + observations.append(Observation(int(count), dict(attributes))) _REQUESTS_MAP[_REQ_SUCCESS_NAME[1]] = 0 return observations @@ -344,14 +338,12 @@ def _get_failure_count(self, options: CallbackOptions) -> Iterable[Observation]: attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) attributes.update(_StatsbeatMetrics._NETWORK_ATTRIBUTES) with _REQUESTS_MAP_LOCK: - for code, count in _REQUESTS_MAP.get(_REQ_FAILURE_NAME[1], {}).items(): # type: ignore + for code, count in _REQUESTS_MAP.get(_REQ_FAILURE_NAME[1], {}).items(): # type: ignore # only observe if value is not 0 if count != 0: attributes["statusCode"] = code - observations.append( - Observation(int(count), dict(attributes)) - ) - _REQUESTS_MAP[_REQ_FAILURE_NAME[1]][code] = 0 # type: ignore + observations.append(Observation(int(count), dict(attributes))) + _REQUESTS_MAP[_REQ_FAILURE_NAME[1]][code] = 0 # type: ignore return observations # pylint: disable=unused-argument @@ -364,11 +356,9 @@ def _get_average_duration(self, options: CallbackOptions) -> Iterable[Observatio interval_duration = _REQUESTS_MAP.get(_REQ_DURATION_NAME[1], 0) interval_count = _REQUESTS_MAP.get("count", 0) # only observe if value is not 0 - if interval_duration > 0 and interval_count > 0: # type: ignore - result = interval_duration / interval_count # type: ignore - observations.append( - Observation(result * 1000, dict(attributes)) - ) + if interval_duration > 0 and interval_count > 0: # type: ignore + result = interval_duration / interval_count # type: ignore + observations.append(Observation(result * 1000, dict(attributes))) _REQUESTS_MAP[_REQ_DURATION_NAME[1]] = 0 _REQUESTS_MAP["count"] = 0 return observations @@ -380,14 +370,12 @@ def _get_retry_count(self, options: CallbackOptions) -> Iterable[Observation]: attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) attributes.update(_StatsbeatMetrics._NETWORK_ATTRIBUTES) with _REQUESTS_MAP_LOCK: - for code, count in _REQUESTS_MAP.get(_REQ_RETRY_NAME[1], {}).items(): # type: ignore + for code, count in _REQUESTS_MAP.get(_REQ_RETRY_NAME[1], {}).items(): # type: ignore # only observe if value is not 0 if count != 0: attributes["statusCode"] = code - observations.append( - Observation(int(count), dict(attributes)) - ) - _REQUESTS_MAP[_REQ_RETRY_NAME[1]][code] = 0 # type: ignore + observations.append(Observation(int(count), dict(attributes))) + _REQUESTS_MAP[_REQ_RETRY_NAME[1]][code] = 0 # type: ignore return observations # pylint: disable=unused-argument @@ -397,14 +385,12 @@ def _get_throttle_count(self, options: CallbackOptions) -> Iterable[Observation] attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) attributes.update(_StatsbeatMetrics._NETWORK_ATTRIBUTES) with _REQUESTS_MAP_LOCK: - for code, count in _REQUESTS_MAP.get(_REQ_THROTTLE_NAME[1], {}).items(): # type: ignore + for code, count in _REQUESTS_MAP.get(_REQ_THROTTLE_NAME[1], {}).items(): # type: ignore # only observe if value is not 0 if count != 0: attributes["statusCode"] = code - observations.append( - Observation(int(count), dict(attributes)) - ) - _REQUESTS_MAP[_REQ_THROTTLE_NAME[1]][code] = 0 # type: ignore + observations.append(Observation(int(count), dict(attributes))) + _REQUESTS_MAP[_REQ_THROTTLE_NAME[1]][code] = 0 # type: ignore return observations # pylint: disable=unused-argument @@ -414,14 +400,12 @@ def _get_exception_count(self, options: CallbackOptions) -> Iterable[Observation attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) attributes.update(_StatsbeatMetrics._NETWORK_ATTRIBUTES) with _REQUESTS_MAP_LOCK: - for code, count in _REQUESTS_MAP.get(_REQ_EXCEPTION_NAME[1], {}).items(): # type: ignore + for code, count in _REQUESTS_MAP.get(_REQ_EXCEPTION_NAME[1], {}).items(): # type: ignore # only observe if value is not 0 if count != 0: attributes["exceptionType"] = code - observations.append( - Observation(int(count), dict(attributes)) - ) - _REQUESTS_MAP[_REQ_EXCEPTION_NAME[1]][code] = 0 # type: ignore + observations.append(Observation(int(count), dict(attributes))) + _REQUESTS_MAP[_REQ_EXCEPTION_NAME[1]][code] = 0 # type: ignore return observations @@ -433,4 +417,5 @@ def _shorten_host(host: str) -> str: host = match.group(1) return host + # cSpell:enable diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_managed_credential.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_managed_credential.py index 0bc26eba66b7..757a4e9b3039 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_managed_credential.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_managed_credential.py @@ -7,6 +7,7 @@ """ # mypy: disable-error-code="attr-defined" import os + # You will need to install azure-identity from azure.identity import ManagedIdentityCredential from opentelemetry import trace @@ -18,8 +19,7 @@ credential = ManagedIdentityCredential(client_id="") exporter = AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"], - credential=credential + os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"], credential=credential ) trace.set_tracer_provider(TracerProvider()) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_secret_credential.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_secret_credential.py index ac31dbfca833..f1f52f242b30 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_secret_credential.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_secret_credential.py @@ -7,6 +7,7 @@ """ # mypy: disable-error-code="attr-defined" import os + # You will need to install azure-identity from azure.identity import ClientSecretCredential from opentelemetry import trace @@ -22,8 +23,7 @@ client_secret="", ) exporter = AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"], - credential=credential + os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"], credential=credential ) trace.set_tracer_provider(TracerProvider()) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_correlate.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_correlate.py index 2b079ff60833..e93f984a5dd5 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_correlate.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_correlate.py @@ -25,9 +25,7 @@ tracer = trace.get_tracer(__name__) set_logger_provider(LoggerProvider()) -exporter = AzureMonitorLogExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorLogExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(exporter)) # Attach LoggingHandler to namespaced logger diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py index 6e50273d64a0..4f421348c343 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py @@ -20,9 +20,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter set_logger_provider(LoggerProvider()) -exporter = AzureMonitorLogExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorLogExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(exporter)) # Attach LoggingHandler to namespaced logger diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_log.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_log.py index e3549e598b04..d1d276a31029 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_log.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_log.py @@ -22,9 +22,7 @@ logger_provider = LoggerProvider() set_logger_provider(logger_provider) -exporter = AzureMonitorLogExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorLogExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(exporter, schedule_delay_millis=60000)) # Attach LoggingHandler to namespaced logger diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_properties.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_properties.py index df0de09d09bf..bb432368d54e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_properties.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_properties.py @@ -20,9 +20,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter set_logger_provider(LoggerProvider()) -exporter = AzureMonitorLogExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorLogExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(exporter)) # Attach LoggingHandler to namespaced logger diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_attributes.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_attributes.py index 294fcb5944e5..243212b8203d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_attributes.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_attributes.py @@ -13,19 +13,13 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter -exporter = AzureMonitorMetricExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorMetricExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) # Metrics are reported every 1 minute reader = PeriodicExportingMetricReader(exporter) metrics.set_meter_provider(MeterProvider(metric_readers=[reader])) -attribute_set1 = { - "key1": "val1" -} -attribute_set2 = { - "key2": "val2" -} +attribute_set1 = {"key1": "val1"} +attribute_set2 = {"key2": "val2"} large_attribute_set = {} for i in range(20): key = "key{}".format(i) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_instruments.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_instruments.py index dd956ff15198..9b51f8de7d4c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_instruments.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_instruments.py @@ -16,17 +16,16 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter -exporter = AzureMonitorMetricExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorMetricExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) # Metrics are reported every 1 minute -reader = PeriodicExportingMetricReader(exporter,export_interval_millis=60000) +reader = PeriodicExportingMetricReader(exporter, export_interval_millis=60000) meter_provider = MeterProvider(metric_readers=[reader]) metrics.set_meter_provider(meter_provider) # Create a namespaced meter meter = metrics.get_meter_provider().get_meter("sample") + # Callback functions for observable instruments def observable_counter_func(options: CallbackOptions) -> Iterable[Observation]: yield Observation(1, {}) @@ -41,14 +40,13 @@ def observable_up_down_counter_func( def observable_gauge_func(options: CallbackOptions) -> Iterable[Observation]: yield Observation(9, {}) + # Counter counter = meter.create_counter("counter") counter.add(1) # Async Counter -observable_counter = meter.create_observable_counter( - "observable_counter", [observable_counter_func] -) +observable_counter = meter.create_observable_counter("observable_counter", [observable_counter_func]) # UpDownCounter updown_counter = meter.create_up_down_counter("updown_counter") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_views.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_views.py index b7caa688c63d..47a67e0d0b08 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_views.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_views.py @@ -14,9 +14,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter -exporter = AzureMonitorMetricExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorMetricExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) # Create a view matching the counter instrument `my.counter` # and configure the new name `my.counter.total` for the result metrics stream change_metric_name_view = View( diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/collector/sample_collector.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/collector/sample_collector.py index a3d07e565344..cc6204744f4e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/collector/sample_collector.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/collector/sample_collector.py @@ -8,7 +8,7 @@ """ # mypy: disable-error-code="attr-defined" import os -from opentelemetry import trace +from opentelemetry import trace # spell-check:ignore grpc from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter @@ -18,20 +18,14 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter -trace.set_tracer_provider( - TracerProvider( - resource=Resource.create({SERVICE_NAME: "my-zipkin-service"}) - ) -) -tracer = trace.get_tracer(__name__) +trace.set_tracer_provider(TracerProvider(resource=Resource.create({SERVICE_NAME: "my-zipkin-service"}))) +tracer = trace.get_tracer(__name__) -exporter = AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) otlp_exporter = OTLPSpanExporter(endpoint="http://localhost:4317") -span_processor = BatchSpanProcessor(otlp_exporter) +span_processor = BatchSpanProcessor(otlp_exporter) trace.get_tracer_provider().add_span_processor(span_processor) with tracer.start_as_current_span("test"): print("Hello world!") -input(...) \ No newline at end of file +input(...) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/__init__.py index 6fcf0de4918d..5b7f7a925cc0 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/__init__.py @@ -1,2 +1,2 @@ # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. \ No newline at end of file +# Licensed under the MIT License. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/apps.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/apps.py index 79d02ec38f25..cfad6058d247 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/apps.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/apps.py @@ -4,5 +4,5 @@ class ExampleConfig(AppConfig): - default_auto_field = 'django.db.models.BigAutoField' - name = 'example' + default_auto_field = "django.db.models.BigAutoField" + name = "example" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/migrations/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/migrations/__init__.py index 6fcf0de4918d..5b7f7a925cc0 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/migrations/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/migrations/__init__.py @@ -1,2 +1,2 @@ # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. \ No newline at end of file +# Licensed under the MIT License. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/urls.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/urls.py index 3d8023a707fa..206b30d99477 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/urls.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/urls.py @@ -5,5 +5,5 @@ from . import views urlpatterns = [ - path('', views.index, name='index'), + path("", views.index, name="index"), ] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/views.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/views.py index da16e5ee393e..723f6b599434 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/views.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/views.py @@ -4,5 +4,6 @@ from django.http import HttpResponse + def index(request): return HttpResponse("Hello, world.") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/manage.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/manage.py index af5923b7667f..0e3b98599fc1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/manage.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/manage.py @@ -15,7 +15,7 @@ def main(): """Run administrative tasks.""" - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample.settings') + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") # Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, wsgi.py, or manage.py, depending on startup method. # If using manage.py, please remove setup from asgi.py and wsgi.py @@ -24,9 +24,7 @@ def main(): # Set up Azure Monitor OpenTelemetry Exporter trace.set_tracer_provider(TracerProvider()) span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -41,5 +39,5 @@ def main(): execute_from_command_line(sys.argv) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/__init__.py index 6fcf0de4918d..5b7f7a925cc0 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/__init__.py @@ -1,2 +1,2 @@ # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. \ No newline at end of file +# Licensed under the MIT License. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/asgi.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/asgi.py index a8326fa20595..8a286716bcc9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/asgi.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/asgi.py @@ -20,7 +20,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") # Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, wsgi.py, or manage.py, depending on startup method. # If using manage.py, please remove setup from asgi.py and wsgi.py @@ -29,9 +29,7 @@ # Set up Azure Monitor OpenTelemetry Exporter trace.set_tracer_provider(TracerProvider()) span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/settings.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/settings.py index 821273b44f85..28f3b356de4a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/settings.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/settings.py @@ -36,52 +36,52 @@ # Application definition INSTALLED_APPS = [ - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", ] MIDDLEWARE = [ - 'django.middleware.security.SecurityMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", ] -ROOT_URLCONF = 'sample.urls' +ROOT_URLCONF = "sample.urls" TEMPLATES = [ { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.debug', - 'django.template.context_processors.request', - 'django.contrib.auth.context_processors.auth', - 'django.contrib.messages.context_processors.messages', + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", ], }, }, ] -WSGI_APPLICATION = 'sample.wsgi.application' +WSGI_APPLICATION = "sample.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': BASE_DIR / 'db.sqlite3', + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", } } @@ -91,16 +91,16 @@ AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] @@ -108,9 +108,9 @@ # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ -LANGUAGE_CODE = 'en-us' +LANGUAGE_CODE = "en-us" -TIME_ZONE = 'UTC' +TIME_ZONE = "UTC" USE_I18N = True @@ -122,11 +122,11 @@ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ -STATIC_URL = '/static/' +STATIC_URL = "/static/" # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field -DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" -# cSpell:enable \ No newline at end of file +# cSpell:enable diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/urls.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/urls.py index 5714ebcfdca2..851a91e5ce26 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/urls.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/urls.py @@ -18,5 +18,5 @@ from django.urls import include, path urlpatterns = [ - path('', include('example.urls')), + path("", include("example.urls")), ] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/wsgi.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/wsgi.py index a079ddc2c133..efff218d22b8 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/wsgi.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/wsgi.py @@ -19,7 +19,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") # Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, wsgi.py, or manage.py, depending on startup method. # If using manage.py, please remove setup from asgi.py and wsgi.py @@ -28,9 +28,7 @@ # Set up Azure Monitor OpenTelemetry Exporter trace.set_tracer_provider(TracerProvider()) span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py index bdb46ba1080c..3fa3108b3f9a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py @@ -28,10 +28,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -43,10 +42,6 @@ with tracer.start_as_current_span(name="AppConfig"): config_setting = ConfigurationSetting( - key="MyKey", - label="MyLabel", - value="my value", - content_type="my content type", - tags={"my tag": "my tag value"} + key="MyKey", label="MyLabel", value="my value", content_type="my content type", tags={"my tag": "my tag value"} ) added_config_setting = client.add_configuration_setting(config_setting) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_blob_checkpoint.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_blob_checkpoint.py index 5f5dc77c125a..003846444495 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_blob_checkpoint.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_blob_checkpoint.py @@ -28,10 +28,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -40,25 +39,24 @@ from azure.eventhub.extensions.checkpointstoreblob import BlobCheckpointStore CONNECTION_STR = os.environ["EVENT_HUB_CONN_STR"] -EVENTHUB_NAME = os.environ['EVENT_HUB_NAME'] +EVENTHUB_NAME = os.environ["EVENT_HUB_NAME"] STORAGE_CONNECTION_STR = os.environ["AZURE_STORAGE_CONN_STR"] BLOB_CONTAINER_NAME = "your-blob-container-name" # Please make sure the blob container resource exists. + def on_event(partition_context, event): # Put your code here. # Avoid time-consuming operations. print(event) partition_context.update_checkpoint(event) + checkpoint_store = BlobCheckpointStore.from_connection_string( STORAGE_CONNECTION_STR, container_name=BLOB_CONTAINER_NAME, ) client = EventHubConsumerClient.from_connection_string( - CONNECTION_STR, - consumer_group='$Default', - eventhub_name=EVENTHUB_NAME, - checkpoint_store=checkpoint_store + CONNECTION_STR, consumer_group="$Default", eventhub_name=EVENTHUB_NAME, checkpoint_store=checkpoint_store ) with tracer.start_as_current_span(name="MyEventHub"): diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_chat.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_chat.py index a5b399950547..fcad00aa8fb4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_chat.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_chat.py @@ -27,16 +27,16 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) # Example with Communication Chat SDKs # Authenticate with Communication Identity SDK from azure.communication.identity import CommunicationIdentityClient + comm_connection_string = "" identity_client = CommunicationIdentityClient.from_connection_string(comm_connection_string) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_phone.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_phone.py index ff1431692ce5..37527ff9b018 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_phone.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_phone.py @@ -27,10 +27,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_sms.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_sms.py index 12b2995b5ee2..db95c0153cc6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_sms.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_sms.py @@ -27,10 +27,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -43,8 +42,9 @@ with tracer.start_as_current_span(name="SendSMS"): sms_responses = sms_client.send( - from_="", - to="", - message="Hello World via SMS", - enable_delivery_report=True, # optional property - tag="custom-tag") # optional property + from_="", + to="", + message="Hello World via SMS", + enable_delivery_report=True, # optional property + tag="custom-tag", + ) # optional property diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_cosmos.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_cosmos.py index c23423f98723..ad9a8f037858 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_cosmos.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_cosmos.py @@ -27,10 +27,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_grid.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_grid.py index b10ea7ae8d6f..d3870db68993 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_grid.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_grid.py @@ -27,10 +27,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -41,12 +40,7 @@ key = os.environ["EG_ACCESS_KEY"] endpoint = os.environ["EG_TOPIC_HOSTNAME"] -event = EventGridEvent( - data={"team": "azure-sdk"}, - subject="Door1", - event_type="Azure.Sdk.Demo", - data_version="2.0" -) +event = EventGridEvent(data={"team": "azure-sdk"}, subject="Door1", event_type="Azure.Sdk.Demo", data_version="2.0") credential = AzureKeyCredential(key) client = EventGridPublisherClient(endpoint, credential) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_hub.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_hub.py index 0c1d4349a684..767f69107171 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_hub.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_hub.py @@ -27,26 +27,22 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) # Example with EventHub SDKs from azure.eventhub import EventHubProducerClient, EventData -CONNECTION_STR = os.environ['EVENT_HUB_CONN_STR'] -EVENTHUB_NAME = os.environ['EVENT_HUB_NAME'] +CONNECTION_STR = os.environ["EVENT_HUB_CONN_STR"] +EVENTHUB_NAME = os.environ["EVENT_HUB_NAME"] -producer = EventHubProducerClient.from_connection_string( - conn_str=CONNECTION_STR, - eventhub_name=EVENTHUB_NAME -) +producer = EventHubProducerClient.from_connection_string(conn_str=CONNECTION_STR, eventhub_name=EVENTHUB_NAME) with tracer.start_as_current_span(name="MyEventHub"): with producer: event_data_batch = producer.create_batch() - event_data_batch.add(EventData('Single message')) + event_data_batch.add(EventData("Single message")) producer.send_batch(event_data_batch) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py index 649312ca8336..167d6c2c6670 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py @@ -26,12 +26,11 @@ trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) + # Requests made to fastapi endpoints will be automatically captured @app.get("/") async def test(): @@ -50,6 +49,7 @@ async def exception(): async def exclude(): return {"message": "Telemetry was not captured"} + if __name__ == "__main__": # cSpell:disable uvicorn.run("sample_fastapi:app", port=8008, reload=True) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_flask.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_flask.py index 85d2caa995b6..4590ff71b8db 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_flask.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_flask.py @@ -26,15 +26,15 @@ trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) + @app.route("/") def test(): return "Test flask request" + if __name__ == "__main__": app.run(host="localhost", port=8080, threaded=True) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_form_recognizer.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_form_recognizer.py index 5ce60ae49eb7..c9c8884058a3 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_form_recognizer.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_form_recognizer.py @@ -28,10 +28,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_jaeger.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_jaeger.py index 59b700bc2b5e..8070792702a1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_jaeger.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_jaeger.py @@ -15,9 +15,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter -exporter = AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) jaeger_exporter = JaegerExporter( agent_host_name="localhost", @@ -25,11 +23,7 @@ ) # Service name needs to be populated for Jaeger to see traces -trace.set_tracer_provider( - TracerProvider( - resource=Resource.create({SERVICE_NAME: "my-jaeger-service"}) - ) -) +trace.set_tracer_provider(TracerProvider(resource=Resource.create({SERVICE_NAME: "my-jaeger-service"}))) tracer = trace.get_tracer(__name__) span_processor = BatchSpanProcessor(exporter) trace.get_tracer_provider().add_span_processor(span_processor) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_cert.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_cert.py index 7fe867250a1f..1b34dcbf908b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_cert.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_cert.py @@ -27,10 +27,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -42,11 +41,7 @@ client_id = "" client_secret = "" -credential = ClientSecretCredential( - tenant_id=tenant_id, - client_id=client_id, - client_secret=client_secret -) +credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret) vault_url = "https://my-key-vault.vault.azure.net/" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_keys.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_keys.py index 73d182172626..89e7e376770c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_keys.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_keys.py @@ -27,10 +27,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -42,11 +41,7 @@ client_id = "" client_secret = "" -credential = ClientSecretCredential( - tenant_id=tenant_id, - client_id=client_id, - client_secret=client_secret -) +credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret) vault_url = "https://my-key-vault.vault.azure.net/" key_client = KeyClient(vault_url=vault_url, credential=credential) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_secret.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_secret.py index 04487040f408..40f4bcbb31b3 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_secret.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_secret.py @@ -27,10 +27,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -42,11 +41,7 @@ client_id = "" client_secret = "" -credential = ClientSecretCredential( - tenant_id=tenant_id, - client_id=client_id, - client_secret=client_secret -) +credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret) vault_url = "https://my-key-vault.vault.azure.net/" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_metrics.py index 2415ab98517b..65e8749b0ad5 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_metrics.py @@ -42,17 +42,17 @@ trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) + @app.route("/") def test(): success_response = requests.get("https://httpstat.us/200", timeout=5) failure_response = requests.get("https://httpstat.us/404", timeout=5) return "Test flask request" + if __name__ == "__main__": app.run(host="localhost", port=8080, threaded=True) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_psycopg2.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_psycopg2.py index b34ea0dd9656..d70e38e244e8 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_psycopg2.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_psycopg2.py @@ -25,13 +25,11 @@ trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -cnx = psycopg2.connect(database='test', user="", password="") +cnx = psycopg2.connect(database="test", user="", password="") cursor = cnx.cursor() cursor.execute("INSERT INTO test_tables (test_field) VALUES (123)") cursor.close() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_requests.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_requests.py index 461006615fef..6c3fc00c4216 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_requests.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_requests.py @@ -23,9 +23,7 @@ trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_sampling.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_sampling.py index 62b4a79ea2d8..bcea97d13308 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_sampling.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_sampling.py @@ -20,9 +20,7 @@ sampler = ApplicationInsightsSampler(0.75) trace.set_tracer_provider(TracerProvider(sampler=sampler)) tracer = trace.get_tracer(__name__) -exporter = AzureMonitorTraceExporter( - connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorTraceExporter(connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) span_processor = BatchSpanProcessor(exporter) trace.get_tracer_provider().add_span_processor(span_processor) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_receive.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_receive.py index 63c843c104fe..a2d78baaf588 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_receive.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_receive.py @@ -29,18 +29,17 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) # Example with Servicebus SDKs from azure.servicebus import ServiceBusClient, ServiceBusMessage -connstr = os.environ['SERVICE_BUS_CONN_STR'] -queue_name = os.environ['SERVICE_BUS_QUEUE_NAME'] +connstr = os.environ["SERVICE_BUS_CONN_STR"] +queue_name = os.environ["SERVICE_BUS_QUEUE_NAME"] with tracer.start_as_current_span(name="MyApplication2"): with ServiceBusClient.from_connection_string(connstr) as client: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_send.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_send.py index d3cdd98571a9..110cdff2f68c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_send.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_send.py @@ -29,18 +29,17 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) # Example with Servicebus SDKs from azure.servicebus import ServiceBusClient, ServiceBusMessage -connstr = os.environ['SERVICE_BUS_CONN_STR'] -queue_name = os.environ['SERVICE_BUS_QUEUE_NAME'] +connstr = os.environ["SERVICE_BUS_CONN_STR"] +queue_name = os.environ["SERVICE_BUS_QUEUE_NAME"] with tracer.start_as_current_span(name="MyApplication"): with ServiceBusClient.from_connection_string(connstr) as client: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py index 944b3a7b8777..8d83b9ffd0e8 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py @@ -12,9 +12,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter -exporter = AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_storage_blob.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_storage_blob.py index e881d74db758..5a6351afa4b1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_storage_blob.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_storage_blob.py @@ -27,18 +27,17 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) # Example with BlobStorage SDKs from azure.storage.blob import BlobServiceClient -connection_string = os.environ['AZURE_STORAGE_CONNECTION_STRING'] -container_name = os.environ['AZURE_STORAGE_BLOB_CONTAINER_NAME'] +connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] +container_name = os.environ["AZURE_STORAGE_BLOB_CONTAINER_NAME"] with tracer.start_as_current_span(name="MyStorageApplication"): client = BlobServiceClient.from_connection_string(connection_string) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_text_analytics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_text_analytics.py index e03f70f88ebf..378ea645eabd 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_text_analytics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_text_analytics.py @@ -28,10 +28,9 @@ # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] - ) + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) @@ -40,7 +39,7 @@ from azure.ai.textanalytics import TextAnalyticsClient credential = AzureKeyCredential("") -endpoint="https://.cognitiveservices.azure.com/" +endpoint = "https://.cognitiveservices.azure.com/" text_analytics_client = TextAnalyticsClient(endpoint, credential) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_trace.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_trace.py index e16740518217..360d0aae1a27 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_trace.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_trace.py @@ -12,9 +12,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter -exporter = AzureMonitorTraceExporter.from_connection_string( - os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] -) +exporter = AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) tracer_provider = TracerProvider() trace.set_tracer_provider(tracer_provider) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/setup.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/setup.py index c25baa25f1a7..61739c223870 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/setup.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/setup.py @@ -19,7 +19,7 @@ PACKAGE_PPRINT_NAME = "Azure Monitor Opentelemetry Exporter" # a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace('-', '/') +package_folder_path = PACKAGE_NAME.replace("-", "/") # azure v0.x is not compatible with this package @@ -30,8 +30,7 @@ try: ver = azure.__version__ raise Exception( - 'This package is incompatible with azure=={}. '.format(ver) + - 'Uninstall it with "pip uninstall azure".' + "This package is incompatible with azure=={}. ".format(ver) + 'Uninstall it with "pip uninstall azure".' ) except AttributeError: pass @@ -39,47 +38,48 @@ pass # Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") setup( name=PACKAGE_NAME, version=version, - description='Microsoft {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), - long_description=open('README.md', 'r').read(), - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='ascl@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-opentelemetry-exporter', + description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=open("README.md", "r").read(), + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="ascl@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-opentelemetry-exporter", keywords="azure, azure sdk", classifiers=[ "Development Status :: 4 - Beta", - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'License :: OSI Approved :: MIT License', + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], zip_safe=False, - packages=find_packages(exclude=[ - 'tests', - 'samples', - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.monitor', - 'azure.monitor.opentelemetry' - ]), + packages=find_packages( + exclude=[ + "tests", + "samples", + # Exclude packages that will be covered by PEP420 or nspkg + "azure", + "azure.monitor", + "azure.monitor.opentelemetry", + ] + ), include_package_data=True, package_data={ - 'pytyped': ['py.typed'], + "pytyped": ["py.typed"], }, python_requires=">=3.8", install_requires=[ @@ -102,8 +102,8 @@ ], "opentelemetry_traces_sampler": [ "azure_monitor_opentelemetry_sampler = azure.monitor.opentelemetry.exporter.export.trace._sampling:azure_monitor_opentelemetry_sampler_factory" - ] - } + ], + }, ) # cSpell:enable diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py index 1f6b527281c3..61d24f22436e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py @@ -1,5 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +import json import os import platform import shutil @@ -42,83 +43,137 @@ def func(*_args, **_kwargs): return func +class NotSerializeableClass: + def __str__(self) -> str: + return "This class is not serializeable" + + # pylint: disable=import-error # pylint: disable=protected-access # pylint: disable=too-many-lines class TestAzureLogExporter(unittest.TestCase): _exporter_class = AzureMonitorLogExporter + @classmethod def setUpClass(cls): os.environ.clear() - os.environ[ - "APPINSIGHTS_INSTRUMENTATIONKEY" - ] = "1234abcd-5678-4efa-8abc-1234567890ab" + os.environ["APPINSIGHTS_INSTRUMENTATIONKEY"] = "1234abcd-5678-4efa-8abc-1234567890ab" os.environ["APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL"] = "true" cls._exporter = cls._exporter_class() cls._log_data = _logs.LogData( _logs.LogRecord( - timestamp = 1646865018558419456, - trace_id = 125960616039069540489478540494783893221, - span_id = 2909973987304607650, - severity_text = "WARNING", - trace_flags = None, - severity_number = SeverityNumber.WARN, - body = "Test message", - resource = Resource.create( - attributes={"asd":"test_resource"} - ), - attributes={ - "test": "attribute" - }, + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="WARNING", + trace_flags=None, + severity_number=SeverityNumber.WARN, + body="Test message", + resource=Resource.create(attributes={"asd": "test_resource"}), + attributes={"test": "attribute"}, ), InstrumentationScope("test_name"), ) cls._log_data_empty = _logs.LogData( _logs.LogRecord( - timestamp = 1646865018558419456, - trace_id = 125960616039069540489478540494783893221, - span_id = 2909973987304607650, - severity_text = "WARNING", - trace_flags = None, - severity_number = SeverityNumber.WARN, - body = "", - resource = Resource.create( - attributes={"asd":"test_resource"} - ), + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="WARNING", + trace_flags=None, + severity_number=SeverityNumber.WARN, + body="", + resource=Resource.create(attributes={"asd": "test_resource"}), + attributes={"test": "attribute"}, + ), + InstrumentationScope("test_name"), + ) + cls._log_data_none = _logs.LogData( + _logs.LogRecord( + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="WARNING", + trace_flags=None, + severity_number=SeverityNumber.WARN, + body=None, + resource=Resource.create(attributes={"asd": "test_resource"}), + attributes={"test": "attribute"}, + ), + InstrumentationScope("test_name"), + ) + cls._log_data_complex_body = _logs.LogData( + _logs.LogRecord( + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="WARNING", + trace_flags=None, + severity_number=SeverityNumber.WARN, + body={"foo": {"bar": "baz", "qux": 42}}, + resource=Resource.create(attributes={"asd": "test_resource"}), + attributes={"test": "attribute"}, + ), + InstrumentationScope("test_name"), + ) + cls._log_data_complex_body_not_serializeable = _logs.LogData( + _logs.LogRecord( + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="WARNING", + trace_flags=None, + severity_number=SeverityNumber.WARN, + body=NotSerializeableClass(), + resource=Resource.create(attributes={"asd": "test_resource"}), + attributes={"test": "attribute"}, + ), + InstrumentationScope("test_name"), + ) + cls._log_data_event = _logs.LogData( + _logs.LogRecord( + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="INFO", + trace_flags=None, + severity_number=SeverityNumber.INFO, + body="Test Event", + resource=Resource.create(attributes={"asd": "test_resource"}), attributes={ - "test": "attribute" + "event_key": "event_attribute", + _APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE: True, }, ), InstrumentationScope("test_name"), ) - cls._log_data_none = _logs.LogData( + cls._log_data_event_complex_body = _logs.LogData( _logs.LogRecord( - timestamp = 1646865018558419456, - trace_id = 125960616039069540489478540494783893221, - span_id = 2909973987304607650, - severity_text = "WARNING", - trace_flags = None, - severity_number = SeverityNumber.WARN, - body = None, - resource = Resource.create( - attributes={"asd":"test_resource"} - ), + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="INFO", + trace_flags=None, + severity_number=SeverityNumber.INFO, + body={"foo": {"bar": "baz", "qux": 42}}, + resource=Resource.create(attributes={"asd": "test_resource"}), attributes={ - "test": "attribute" + "event_key": "event_attribute", + _APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE: True, }, ), InstrumentationScope("test_name"), ) - cls._log_data_event = _logs.LogData( + cls._log_data_event_complex_body_not_serializeable = _logs.LogData( _logs.LogRecord( - timestamp = 1646865018558419456, - trace_id = 125960616039069540489478540494783893221, - span_id = 2909973987304607650, - severity_text = "INFO", - trace_flags = None, - severity_number = SeverityNumber.INFO, - body = "Test Event", - resource = Resource.create(attributes={"asd":"test_resource"}), + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="INFO", + trace_flags=None, + severity_number=SeverityNumber.INFO, + body=NotSerializeableClass(), + resource=Resource.create(attributes={"asd": "test_resource"}), attributes={ "event_key": "event_attribute", _APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE: True, @@ -128,85 +183,67 @@ def setUpClass(cls): ) cls._exc_data = _logs.LogData( _logs.LogRecord( - timestamp = 1646865018558419456, - trace_id = 125960616039069540489478540494783893221, - span_id = 2909973987304607650, - severity_text = "EXCEPTION", - trace_flags = None, - severity_number = SeverityNumber.FATAL, - body = "Test message", - resource = Resource.create( - attributes={"asd":"test_resource"} - ), + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="EXCEPTION", + trace_flags=None, + severity_number=SeverityNumber.FATAL, + body="Test message", + resource=Resource.create(attributes={"asd": "test_resource"}), attributes={ "test": "attribute", EXCEPTION_TYPE: "ZeroDivisionError", EXCEPTION_MESSAGE: "division by zero", - EXCEPTION_STACKTRACE: 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n' + EXCEPTION_STACKTRACE: 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n', }, ), InstrumentationScope("test_name"), ) cls._exc_data_with_exc_body = _logs.LogData( _logs.LogRecord( - timestamp = 1646865018558419456, - trace_id = 125960616039069540489478540494783893221, - span_id = 2909973987304607650, - severity_text = "EXCEPTION", - trace_flags = None, - severity_number = SeverityNumber.FATAL, - body = Exception("test exception message"), - resource = Resource.create( - attributes={"asd":"test_resource"} - ), + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="EXCEPTION", + trace_flags=None, + severity_number=SeverityNumber.FATAL, + body=Exception("test exception message"), + resource=Resource.create(attributes={"asd": "test_resource"}), attributes={ "test": "attribute", EXCEPTION_TYPE: "ZeroDivisionError", EXCEPTION_MESSAGE: "division by zero", - EXCEPTION_STACKTRACE: 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n' + EXCEPTION_STACKTRACE: 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n', }, ), InstrumentationScope("test_name"), ) cls._exc_data_blank_exception = _logs.LogData( _logs.LogRecord( - timestamp = 1646865018558419456, - trace_id = 125960616039069540489478540494783893221, - span_id = 2909973987304607650, - severity_text = "EXCEPTION", - trace_flags = None, - severity_number = SeverityNumber.FATAL, - body = "test exception", - resource = Resource.create( - attributes={"asd":"test_resource"} - ), - attributes={ - "test": "attribute", - EXCEPTION_TYPE: "", - EXCEPTION_MESSAGE: "", - EXCEPTION_STACKTRACE: "" - }, + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="EXCEPTION", + trace_flags=None, + severity_number=SeverityNumber.FATAL, + body="test exception", + resource=Resource.create(attributes={"asd": "test_resource"}), + attributes={"test": "attribute", EXCEPTION_TYPE: "", EXCEPTION_MESSAGE: "", EXCEPTION_STACKTRACE: ""}, ), InstrumentationScope("test_name"), ) cls._exc_data_empty = _logs.LogData( _logs.LogRecord( - timestamp = 1646865018558419456, - trace_id = 125960616039069540489478540494783893221, - span_id = 2909973987304607650, - severity_text = "EXCEPTION", - trace_flags = None, - severity_number = SeverityNumber.FATAL, - body = "", - resource = Resource.create( - attributes={"asd":"test_resource"} - ), - attributes={ - "test": "attribute", - EXCEPTION_TYPE: "", - EXCEPTION_MESSAGE: "", - EXCEPTION_STACKTRACE: "" - }, + timestamp=1646865018558419456, + trace_id=125960616039069540489478540494783893221, + span_id=2909973987304607650, + severity_text="EXCEPTION", + trace_flags=None, + severity_number=SeverityNumber.FATAL, + body="", + resource=Resource.create(attributes={"asd": "test_resource"}), + attributes={"test": "attribute", EXCEPTION_TYPE: "", EXCEPTION_MESSAGE: "", EXCEPTION_STACKTRACE: ""}, ), InstrumentationScope("test_name"), ) @@ -289,20 +326,34 @@ def test_log_to_envelope_partA(self): exporter = self._exporter old_resource = self._log_data.log_record.resource resource = Resource( - {"service.name": "testServiceName", - "service.namespace": "testServiceNamespace", - "service.instance.id": "testServiceInstanceId"}) + { + "service.name": "testServiceName", + "service.namespace": "testServiceNamespace", + "service.instance.id": "testServiceInstanceId", + } + ) self._log_data.log_record.resource = resource envelope = exporter._log_to_envelope(self._log_data) - self.assertEqual(envelope.instrumentation_key, - "1234abcd-5678-4efa-8abc-1234567890ab") + self.assertEqual(envelope.instrumentation_key, "1234abcd-5678-4efa-8abc-1234567890ab") self.assertIsNotNone(envelope.tags) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION]) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), + azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION], + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), + azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION], + ) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE), "testServiceNamespace.testServiceName") self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), "testServiceInstanceId") @@ -316,22 +367,24 @@ def test_log_to_envelope_partA(self): def test_log_to_envelope_partA_default(self): exporter = self._exporter old_resource = self._log_data.log_record.resource - resource = Resource( - {"service.name": "testServiceName"}) + resource = Resource({"service.name": "testServiceName"}) self._log_data.log_record.resource = resource envelope = exporter._log_to_envelope(self._log_data) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE), "testServiceName") self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), platform.node()) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_NODE_NAME), envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE)) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_NODE_NAME), + envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), + ) self._log_data.log_record.resource = old_resource def test_log_to_envelope_log(self): exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data) record = self._log_data.log_record - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Message') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp)) - self.assertEqual(envelope.data.base_type, 'MessageData') + self.assertEqual(envelope.data.base_type, "MessageData") self.assertEqual(envelope.data.base_data.message, record.body) self.assertEqual(envelope.data.base_data.severity_level, 2) self.assertEqual(envelope.data.base_data.properties["test"], "attribute") @@ -339,54 +392,76 @@ def test_log_to_envelope_log(self): def test_log_to_envelope_log_none(self): exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_none) - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Message') - self.assertEqual(envelope.data.base_type, 'MessageData') - self.assertEqual(envelope.data.base_data.message, "n/a") + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") + self.assertEqual(envelope.data.base_type, "MessageData") + self.assertEqual(envelope.data.base_data.message, "") def test_log_to_envelope_log_empty(self): exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_empty) - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Message') - self.assertEqual(envelope.data.base_type, 'MessageData') - self.assertEqual(envelope.data.base_data.message, "n/a") + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") + self.assertEqual(envelope.data.base_type, "MessageData") + self.assertEqual(envelope.data.base_data.message, "") + + def test_log_to_envelope_log_complex_body(self): + exporter = self._exporter + envelope = exporter._log_to_envelope(self._log_data_complex_body) + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") + self.assertEqual(envelope.data.base_type, "MessageData") + self.assertEqual(envelope.data.base_data.message, json.dumps(self._log_data_complex_body.log_record.body)) + + def test_log_to_envelope_log_complex_body_not_serializeable(self): + exporter = self._exporter + envelope = exporter._log_to_envelope(self._log_data_complex_body_not_serializeable) + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") + self.assertEqual(envelope.data.base_type, "MessageData") + self.assertEqual( + envelope.data.base_data.message, str(self._log_data_complex_body_not_serializeable.log_record.body) + ) def test_log_to_envelope_exception_with_string_message(self): exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data) record = self._log_data.log_record - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Exception') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Exception") self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp)) - self.assertEqual(envelope.data.base_type, 'ExceptionData') + self.assertEqual(envelope.data.base_type, "ExceptionData") self.assertEqual(envelope.data.base_data.severity_level, 4) self.assertEqual(envelope.data.base_data.properties["test"], "attribute") self.assertEqual(len(envelope.data.base_data.exceptions), 1) self.assertEqual(envelope.data.base_data.exceptions[0].type_name, "ZeroDivisionError") self.assertEqual(envelope.data.base_data.exceptions[0].message, "Test message") self.assertTrue(envelope.data.base_data.exceptions[0].has_full_stack) - self.assertEqual(envelope.data.base_data.exceptions[0].stack, 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n') + self.assertEqual( + envelope.data.base_data.exceptions[0].stack, + 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n', + ) def test_log_to_envelope_exception_with_exc_message(self): exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data_with_exc_body) record = self._log_data.log_record - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Exception') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Exception") self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp)) - self.assertEqual(envelope.data.base_type, 'ExceptionData') + self.assertEqual(envelope.data.base_type, "ExceptionData") self.assertEqual(envelope.data.base_data.severity_level, 4) self.assertEqual(envelope.data.base_data.properties["test"], "attribute") self.assertEqual(len(envelope.data.base_data.exceptions), 1) self.assertEqual(envelope.data.base_data.exceptions[0].type_name, "ZeroDivisionError") self.assertEqual(envelope.data.base_data.exceptions[0].message, "test exception message") self.assertTrue(envelope.data.base_data.exceptions[0].has_full_stack) - self.assertEqual(envelope.data.base_data.exceptions[0].stack, 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n') + self.assertEqual( + envelope.data.base_data.exceptions[0].stack, + 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n', + ) def test_log_to_envelope_exception_empty(self): exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data_empty) record = self._log_data.log_record - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Exception') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Exception") self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp)) - self.assertEqual(envelope.data.base_type, 'ExceptionData') + self.assertEqual(envelope.data.base_type, "ExceptionData") self.assertEqual(envelope.data.base_data.severity_level, 4) self.assertEqual(envelope.data.base_data.properties["test"], "attribute") self.assertEqual(len(envelope.data.base_data.exceptions), 1) @@ -399,9 +474,9 @@ def test_log_to_envelope_exception_with_blank_exception(self): exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data_blank_exception) record = self._log_data.log_record - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Exception') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Exception") self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp)) - self.assertEqual(envelope.data.base_type, 'ExceptionData') + self.assertEqual(envelope.data.base_type, "ExceptionData") self.assertEqual(envelope.data.base_data.severity_level, 4) self.assertEqual(envelope.data.base_data.properties["test"], "attribute") self.assertEqual(len(envelope.data.base_data.exceptions), 1) @@ -414,12 +489,32 @@ def test_log_to_envelope_event(self): exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_event) record = self._log_data_event.log_record - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Event') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Event") self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp)) - self.assertEqual(envelope.data.base_type, 'EventData') + self.assertEqual(envelope.data.base_type, "EventData") self.assertEqual(envelope.data.base_data.name, record.body) self.assertEqual(envelope.data.base_data.properties["event_key"], "event_attribute") + def test_log_to_envelope_event_complex_body(self): + exporter = self._exporter + envelope = exporter._log_to_envelope(self._log_data_event_complex_body) + record = self._log_data_event_complex_body.log_record + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Event") + self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp)) + self.assertEqual(envelope.data.base_type, "EventData") + self.assertEqual(envelope.data.base_data.name, json.dumps(record.body)) + self.assertEqual(envelope.data.base_data.properties["event_key"], "event_attribute") + + def test_log_to_envelope_event_complex_body_not_serializeable(self): + exporter = self._exporter + envelope = exporter._log_to_envelope(self._log_data_event_complex_body_not_serializeable) + record = self._log_data_event_complex_body_not_serializeable.log_record + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Event") + self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp)) + self.assertEqual(envelope.data.base_type, "EventData") + self.assertEqual(envelope.data.base_data.name, str(record.body)) + self.assertEqual(envelope.data.base_data.properties["event_key"], "event_attribute") + def test_log_to_envelope_timestamp(self): exporter = self._exporter old_record = self._log_data.log_record @@ -429,15 +524,15 @@ def test_log_to_envelope_timestamp(self): record = self._log_data.log_record self.assertEqual(envelope.time, ns_to_iso_str(record.observed_timestamp)) self._log_data.log_record = old_record - + class TestAzureLogExporterWithDisabledStorage(TestAzureLogExporter): _exporter_class = partial(AzureMonitorLogExporter, disable_offline_storage=True) - + @classmethod def tearDownClass(cls): pass - + def test_constructor(self): """Test the constructor.""" exporter = AzureMonitorLogExporter( @@ -449,12 +544,12 @@ def test_constructor(self): "4321abcd-5678-4efa-8abc-1234567890ab", ) self.assertEqual(exporter.storage, None) - + def test_shutdown(self): exporter = self._exporter exporter.shutdown() self.assertEqual(exporter.storage, None) - + def test_export_failure(self): exporter = self._exporter with mock.patch( @@ -495,23 +590,20 @@ def test_get_log_export_result(self): _get_log_export_result(ExportResult.FAILED_RETRYABLE), LogExportResult.FAILURE, ) - self.assertEqual( - _get_log_export_result(None), - LogExportResult.FAILURE - ) + self.assertEqual(_get_log_export_result(None), LogExportResult.FAILURE) def test_get_severity_level(self): for sev_num in SeverityNumber: num = sev_num.value level = _get_severity_level(sev_num) print(num) - if num in range(0,9): + if num in range(0, 9): self.assertEqual(level, 0) - elif num in range(9,13): + elif num in range(9, 13): self.assertEqual(level, 1) - elif num in range(13,17): + elif num in range(13, 17): self.assertEqual(level, 2) - elif num in range(17,21): + elif num in range(17, 21): self.assertEqual(level, 3) else: self.assertEqual(level, 4) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py index c372670699cc..c771546ce3d7 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py @@ -47,17 +47,13 @@ class TestAzureMetricExporter(unittest.TestCase): @classmethod def setUpClass(cls): os.environ.clear() - os.environ[ - "APPINSIGHTS_INSTRUMENTATIONKEY" - ] = "1234abcd-5678-4efa-8abc-1234567890ab" + os.environ["APPINSIGHTS_INSTRUMENTATIONKEY"] = "1234abcd-5678-4efa-8abc-1234567890ab" os.environ["APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL"] = "true" cls._exporter = AzureMonitorMetricExporter() cls._metrics_data = MetricsData( resource_metrics=[ ResourceMetrics( - resource = Resource.create( - attributes={"asd":"test_resource"} - ), + resource=Resource.create(attributes={"asd": "test_resource"}), scope_metrics=[ ScopeMetrics( scope=InstrumentationScope("test_name"), @@ -79,7 +75,7 @@ def setUpClass(cls): ], aggregation_temporality=AggregationTemporality.CUMULATIVE, is_monotonic=False, - ) + ), ) ], schema_url="test url", @@ -166,10 +162,13 @@ def test_export_not_retryable(self): def test_point_to_envelope_partA(self): exporter = self._exporter resource = Resource( - {"service.name": "testServiceName", - "service.namespace": "testServiceNamespace", - "service.instance.id": "testServiceInstanceId"}) - point=NumberDataPoint( + { + "service.name": "testServiceName", + "service.namespace": "testServiceNamespace", + "service.instance.id": "testServiceInstanceId", + } + ) + point = NumberDataPoint( attributes={ "test": "attribute", }, @@ -181,11 +180,23 @@ def test_point_to_envelope_partA(self): self.assertEqual(envelope.instrumentation_key, exporter._instrumentation_key) self.assertIsNotNone(envelope.tags) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION]) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), + azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION], + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), + azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION], + ) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE), "testServiceNamespace.testServiceName") self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), "testServiceInstanceId") @@ -193,9 +204,8 @@ def test_point_to_envelope_partA(self): def test_point_to_envelope_partA_default(self): exporter = self._exporter - resource = Resource( - {"service.name": "testServiceName"}) - point=NumberDataPoint( + resource = Resource({"service.name": "testServiceName"}) + point = NumberDataPoint( attributes={ "test": "attribute", }, @@ -206,13 +216,16 @@ def test_point_to_envelope_partA_default(self): envelope = exporter._point_to_envelope(point, "test name", resource) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE), "testServiceName") self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), platform.node()) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_NODE_NAME), envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE)) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_NODE_NAME), + envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), + ) def test_point_to_envelope_number(self): exporter = self._exporter - resource = Resource.create(attributes={"asd":"test_resource"}) + resource = Resource.create(attributes={"asd": "test_resource"}) scope = InstrumentationScope("test_scope") - point=NumberDataPoint( + point = NumberDataPoint( attributes={ "test": "attribute", }, @@ -222,11 +235,11 @@ def test_point_to_envelope_number(self): ) envelope = exporter._point_to_envelope(point, "test name", resource, scope) self.assertEqual(envelope.instrumentation_key, exporter._instrumentation_key) - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Metric') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Metric") self.assertEqual(envelope.time, ns_to_iso_str(point.time_unix_nano)) - self.assertEqual(envelope.data.base_type, 'MetricData') + self.assertEqual(envelope.data.base_type, "MetricData") self.assertEqual(len(envelope.data.base_data.properties), 1) - self.assertEqual(envelope.data.base_data.properties['test'], 'attribute') + self.assertEqual(envelope.data.base_data.properties["test"], "attribute") self.assertEqual(len(envelope.data.base_data.metrics), 1) self.assertEqual(envelope.data.base_data.metrics[0].name, "test name") self.assertEqual(envelope.data.base_data.metrics[0].namespace, None) @@ -235,14 +248,14 @@ def test_point_to_envelope_number(self): def test_point_to_envelope_histogram(self): exporter = self._exporter - resource = Resource.create(attributes={"asd":"test_resource"}) - point=HistogramDataPoint( + resource = Resource.create(attributes={"asd": "test_resource"}) + point = HistogramDataPoint( attributes={ "test": "attribute", }, - bucket_counts=[0,3,4], + bucket_counts=[0, 3, 4], count=7, - explicit_bounds=[0,5,10,0], + explicit_bounds=[0, 5, 10, 0], max=18, min=1, start_time_unix_nano=1646865018558419456, @@ -251,11 +264,11 @@ def test_point_to_envelope_histogram(self): ) envelope = exporter._point_to_envelope(point, "test name", resource) self.assertEqual(envelope.instrumentation_key, exporter._instrumentation_key) - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Metric') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Metric") self.assertEqual(envelope.time, ns_to_iso_str(point.time_unix_nano)) - self.assertEqual(envelope.data.base_type, 'MetricData') + self.assertEqual(envelope.data.base_type, "MetricData") self.assertEqual(len(envelope.data.base_data.properties), 1) - self.assertEqual(envelope.data.base_data.properties['test'], 'attribute') + self.assertEqual(envelope.data.base_data.properties["test"], "attribute") self.assertEqual(len(envelope.data.base_data.metrics), 1) self.assertEqual(envelope.data.base_data.metrics[0].name, "test name") self.assertEqual(envelope.data.base_data.metrics[0].value, 31) @@ -269,9 +282,9 @@ def test_point_to_envelope_histogram(self): ) def test_point_to_envelope_metric_namespace(self): exporter = self._exporter - resource = Resource.create(attributes={"asd":"test_resource"}) + resource = Resource.create(attributes={"asd": "test_resource"}) scope = InstrumentationScope("test_scope") - point=NumberDataPoint( + point = NumberDataPoint( attributes={ "test": "attribute", }, @@ -281,11 +294,11 @@ def test_point_to_envelope_metric_namespace(self): ) envelope = exporter._point_to_envelope(point, "test name", resource, scope) self.assertEqual(envelope.instrumentation_key, exporter._instrumentation_key) - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Metric') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Metric") self.assertEqual(envelope.time, ns_to_iso_str(point.time_unix_nano)) - self.assertEqual(envelope.data.base_type, 'MetricData') + self.assertEqual(envelope.data.base_type, "MetricData") self.assertEqual(len(envelope.data.base_data.properties), 1) - self.assertEqual(envelope.data.base_data.properties['test'], 'attribute') + self.assertEqual(envelope.data.base_data.properties["test"], "attribute") self.assertEqual(len(envelope.data.base_data.metrics), 1) self.assertEqual(envelope.data.base_data.metrics[0].name, "test name") self.assertEqual(envelope.data.base_data.metrics[0].namespace, "test_scope") @@ -295,10 +308,13 @@ def test_point_to_envelope_metric_namespace(self): def test_point_to_envelope_std_metric_client_duration(self): exporter = self._exporter resource = Resource( - {"service.name": "testServiceName", - "service.namespace": "testServiceNamespace", - "service.instance.id": "testServiceInstanceId"}) - point=NumberDataPoint( + { + "service.name": "testServiceName", + "service.namespace": "testServiceNamespace", + "service.instance.id": "testServiceInstanceId", + } + ) + point = NumberDataPoint( attributes={ "http.status_code": 200, "peer.service": "test_service", @@ -310,17 +326,17 @@ def test_point_to_envelope_std_metric_client_duration(self): ) envelope = exporter._point_to_envelope(point, "http.client.duration", resource) self.assertEqual(envelope.instrumentation_key, exporter._instrumentation_key) - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Metric') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Metric") self.assertEqual(envelope.time, ns_to_iso_str(point.time_unix_nano)) - self.assertEqual(envelope.data.base_type, 'MetricData') - self.assertEqual(envelope.data.base_data.properties['_MS.MetricId'], 'dependencies/duration') - self.assertEqual(envelope.data.base_data.properties['_MS.IsAutocollected'], 'True') - self.assertEqual(envelope.data.base_data.properties['Dependency.Type'], 'http') - self.assertEqual(envelope.data.base_data.properties['Dependency.Success'], 'True') - self.assertEqual(envelope.data.base_data.properties['dependency/target'], 'test_service') - self.assertEqual(envelope.data.base_data.properties['dependency/resultCode'], '200') - self.assertEqual(envelope.data.base_data.properties['cloud/roleInstance'], 'testServiceInstanceId') - self.assertEqual(envelope.data.base_data.properties['cloud/roleName'], 'testServiceNamespace.testServiceName') + self.assertEqual(envelope.data.base_type, "MetricData") + self.assertEqual(envelope.data.base_data.properties["_MS.MetricId"], "dependencies/duration") + self.assertEqual(envelope.data.base_data.properties["_MS.IsAutocollected"], "True") + self.assertEqual(envelope.data.base_data.properties["Dependency.Type"], "http") + self.assertEqual(envelope.data.base_data.properties["Dependency.Success"], "True") + self.assertEqual(envelope.data.base_data.properties["dependency/target"], "test_service") + self.assertEqual(envelope.data.base_data.properties["dependency/resultCode"], "200") + self.assertEqual(envelope.data.base_data.properties["cloud/roleInstance"], "testServiceInstanceId") + self.assertEqual(envelope.data.base_data.properties["cloud/roleName"], "testServiceNamespace.testServiceName") self.assertIsNone(envelope.data.base_data.properties.get("custom_attr")) self.assertEqual(len(envelope.data.base_data.metrics), 1) self.assertEqual(envelope.data.base_data.metrics[0].name, "http.client.duration") @@ -330,36 +346,38 @@ def test_point_to_envelope_std_metric_client_duration(self): point.attributes.pop("peer.service", None) point.attributes["net.peer.name"] = None envelope = exporter._point_to_envelope(point, "http.client.duration", resource) - self.assertEqual(envelope.data.base_data.properties['dependency/target'], None) + self.assertEqual(envelope.data.base_data.properties["dependency/target"], None) point.attributes["net.peer.name"] = "test_peer_name" point.attributes["net.host.port"] = "test_port" envelope = exporter._point_to_envelope(point, "http.client.duration", resource) - self.assertEqual(envelope.data.base_data.properties['dependency/target'], "test_peer_name:test_port") + self.assertEqual(envelope.data.base_data.properties["dependency/target"], "test_peer_name:test_port") # Success/Failure point.attributes["http.status_code"] = 500 envelope = exporter._point_to_envelope(point, "http.client.duration", resource) - self.assertEqual(envelope.data.base_data.properties['Dependency.Success'], "False") + self.assertEqual(envelope.data.base_data.properties["Dependency.Success"], "False") point.attributes["http.status_code"] = None envelope = exporter._point_to_envelope(point, "http.client.duration", resource) - self.assertEqual(envelope.data.base_data.properties['Dependency.Success'], "False") - self.assertEqual(envelope.data.base_data.properties['dependency/resultCode'], "0") + self.assertEqual(envelope.data.base_data.properties["Dependency.Success"], "False") + self.assertEqual(envelope.data.base_data.properties["dependency/resultCode"], "0") point.attributes["http.status_code"] = "None" envelope = exporter._point_to_envelope(point, "http.client.duration", resource) - self.assertEqual(envelope.data.base_data.properties['Dependency.Success'], "False") - self.assertEqual(envelope.data.base_data.properties['dependency/resultCode'], "0") - + self.assertEqual(envelope.data.base_data.properties["Dependency.Success"], "False") + self.assertEqual(envelope.data.base_data.properties["dependency/resultCode"], "0") def test_point_to_envelope_std_metric_server_duration(self): exporter = self._exporter resource = Resource( - {"service.name": "testServiceName", - "service.namespace": "testServiceNamespace", - "service.instance.id": "testServiceInstanceId"}) - point=NumberDataPoint( + { + "service.name": "testServiceName", + "service.namespace": "testServiceNamespace", + "service.instance.id": "testServiceInstanceId", + } + ) + point = NumberDataPoint( attributes={ "http.status_code": 200, "peer.service": "test_service", @@ -371,15 +389,15 @@ def test_point_to_envelope_std_metric_server_duration(self): ) envelope = exporter._point_to_envelope(point, "http.server.duration", resource) self.assertEqual(envelope.instrumentation_key, exporter._instrumentation_key) - self.assertEqual(envelope.name, 'Microsoft.ApplicationInsights.Metric') + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Metric") self.assertEqual(envelope.time, ns_to_iso_str(point.time_unix_nano)) - self.assertEqual(envelope.data.base_type, 'MetricData') - self.assertEqual(envelope.data.base_data.properties['_MS.MetricId'], 'requests/duration') - self.assertEqual(envelope.data.base_data.properties['_MS.IsAutocollected'], 'True') - self.assertEqual(envelope.data.base_data.properties['Request.Success'], 'True') - self.assertEqual(envelope.data.base_data.properties['request/resultCode'], '200') - self.assertEqual(envelope.data.base_data.properties['cloud/roleInstance'], 'testServiceInstanceId') - self.assertEqual(envelope.data.base_data.properties['cloud/roleName'], 'testServiceNamespace.testServiceName') + self.assertEqual(envelope.data.base_type, "MetricData") + self.assertEqual(envelope.data.base_data.properties["_MS.MetricId"], "requests/duration") + self.assertEqual(envelope.data.base_data.properties["_MS.IsAutocollected"], "True") + self.assertEqual(envelope.data.base_data.properties["Request.Success"], "True") + self.assertEqual(envelope.data.base_data.properties["request/resultCode"], "200") + self.assertEqual(envelope.data.base_data.properties["cloud/roleInstance"], "testServiceInstanceId") + self.assertEqual(envelope.data.base_data.properties["cloud/roleName"], "testServiceNamespace.testServiceName") self.assertIsNone(envelope.data.base_data.properties.get("custom_attr")) self.assertEqual(len(envelope.data.base_data.metrics), 1) self.assertEqual(envelope.data.base_data.metrics[0].name, "http.server.duration") @@ -388,26 +406,28 @@ def test_point_to_envelope_std_metric_server_duration(self): # Success/Failure point.attributes["http.status_code"] = 500 envelope = exporter._point_to_envelope(point, "http.server.duration", resource) - self.assertEqual(envelope.data.base_data.properties['Request.Success'], "False") + self.assertEqual(envelope.data.base_data.properties["Request.Success"], "False") point.attributes["http.status_code"] = None envelope = exporter._point_to_envelope(point, "http.server.duration", resource) - self.assertEqual(envelope.data.base_data.properties['Request.Success'], "False") - self.assertEqual(envelope.data.base_data.properties.get('request/resultCode'), "0") + self.assertEqual(envelope.data.base_data.properties["Request.Success"], "False") + self.assertEqual(envelope.data.base_data.properties.get("request/resultCode"), "0") point.attributes["http.status_code"] = "None" envelope = exporter._point_to_envelope(point, "http.server.duration", resource) - self.assertEqual(envelope.data.base_data.properties['Request.Success'], "False") - self.assertEqual(envelope.data.base_data.properties.get('request/resultCode'), "0") - + self.assertEqual(envelope.data.base_data.properties["Request.Success"], "False") + self.assertEqual(envelope.data.base_data.properties.get("request/resultCode"), "0") def test_point_to_envelope_std_metric_unsupported(self): exporter = self._exporter resource = Resource( - {"service.name": "testServiceName", - "service.namespace": "testServiceNamespace", - "service.instance.id": "testServiceInstanceId"}) - point=NumberDataPoint( + { + "service.name": "testServiceName", + "service.namespace": "testServiceNamespace", + "service.instance.id": "testServiceInstanceId", + } + ) + point = NumberDataPoint( attributes={ "http.status_code": 200, "peer.service": "test_service", diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/perfstress_tests/trace_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/perfstress_tests/trace_exporter.py index 168798b80186..9f87aaa27808 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/perfstress_tests/trace_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/perfstress_tests/trace_exporter.py @@ -1,8 +1,8 @@ -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- from devtools_testutils.perfstress_tests import PerfStressTest @@ -13,6 +13,7 @@ from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + class MonitorExporterPerfTest(PerfStressTest): def __init__(self, arguments): super().__init__(arguments) @@ -27,14 +28,12 @@ def __init__(self, arguments): tracer = trace.get_tracer(__name__) self.spans_list = [] for _ in range(self.args.num_spans): - with tracer.start_as_current_span( - name="name" - ) as span: + with tracer.start_as_current_span(name="name") as span: self.spans_list.append(span) def run_sync(self): """The synchronous perf test. - + Try to keep this minimal and focused. Using only a single client API. Avoid putting any ancillary logic (e.g. generating UUIDs), and put this in the setup/init instead so that we're only measuring the client API call. @@ -44,4 +43,6 @@ def run_sync(self): @staticmethod def add_arguments(parser): super(MonitorExporterPerfTest, MonitorExporterPerfTest).add_arguments(parser) - parser.add_argument('-n', '--num-spans', nargs='?', type=int, help='Number of spans to be exported. Defaults to 10', default=10) + parser.add_argument( + "-n", "--num-spans", nargs="?", type=int, help="Number of spans to be exported. Defaults to 10", default=10 + ) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py index ae818f089234..2f5df7b29a24 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py @@ -72,7 +72,7 @@ def setUpClass(cls): ], aggregation_temporality=AggregationTemporality.DELTA, is_monotonic=True, - ) + ), ) ], schema_url="test_url", @@ -98,7 +98,6 @@ def setUpClass(cls): cls._data_point, ) - @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient") def test_init(self, client_mock): exporter = _QuickpulseExporter( @@ -108,12 +107,10 @@ def test_init(self, client_mock): self.assertEqual(exporter._instrumentation_key, "4321abcd-5678-4efa-8abc-1234567890ab") self.assertTrue(isinstance(exporter._client, QuickpulseClient)) - def test_export_missing_data_point(self): result = self._exporter.export(OTMetricsData(resource_metrics=[])) self.assertEqual(result, MetricExportResult.FAILURE) - @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points") def test_export_subscribed_false(self, convert_mock, post_mock): @@ -122,27 +119,20 @@ def test_export_subscribed_false(self, convert_mock, post_mock): None, { "x-ms-qps-subscribed": "false", - } + }, ) convert_mock.return_value = [self._data_point] post_mock.return_value = post_response - result = self._exporter.export( - self._metrics_data, - base_monitoring_data_point=self._data_point - ) + result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point) self.assertEqual(result, MetricExportResult.FAILURE) - @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points") def test_export_subscribed_none(self, convert_mock, post_mock): post_response = None convert_mock.return_value = [self._data_point] post_mock.return_value = post_response - result = self._exporter.export( - self._metrics_data, - base_monitoring_data_point=self._data_point - ) + result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point) self.assertEqual(result, MetricExportResult.FAILURE) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points") @@ -157,10 +147,7 @@ def test_export_exception(self, convert_mock): "azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish", throw(Exception), ): # noqa: E501 - result = self._exporter.export( - self._metrics_data, - base_monitoring_data_point=self._data_point - ) + result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point) self.assertEqual(result, MetricExportResult.FAILURE) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish") @@ -171,14 +158,11 @@ def test_export_subscribed_true(self, convert_mock, post_mock): None, { "x-ms-qps-subscribed": "true", - } + }, ) convert_mock.return_value = [self._data_point] post_mock.return_value = post_response - result = self._exporter.export( - self._metrics_data, - base_monitoring_data_point=self._data_point - ) + result = self._exporter.export(self._metrics_data, base_monitoring_data_point=self._data_point) self.assertEqual(result, MetricExportResult.SUCCESS) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.is_subscribed") @@ -188,12 +172,10 @@ def test_ping(self, ping_mock): None, { "x-ms-qps-subscribed": "false", - } + }, ) ping_mock.return_value = ping_response - response = self._exporter._ping( - monitoring_data_point=self._data_point - ) + response = self._exporter._ping(monitoring_data_point=self._data_point) self.assertEqual(response, ping_response) def test_ping_exception(self): @@ -201,12 +183,9 @@ def test_ping_exception(self): "azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.is_subscribed", throw(HttpResponseError), ): # noqa: E501 - response = self._exporter._ping( - monitoring_data_point=self._data_point - ) + response = self._exporter._ping(monitoring_data_point=self._data_point) self.assertIsNone(response) - @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask") def test_quickpulsereader_init(self, task_mock): task_inst_mock = mock.Mock() @@ -239,13 +218,7 @@ def test_quickpulsereader_ticker_ping_true(self, task_mock, ping_mock): ) _set_global_quickpulse_state(_QuickpulseState.PING_SHORT) reader._elapsed_num_seconds = _QuickpulseState.PING_SHORT.value - ping_mock.return_value = _Response( - None, - None, - { - "x-ms-qps-subscribed": "true" - } - ) + ping_mock.return_value = _Response(None, None, {"x-ms-qps-subscribed": "true"}) reader._ticker() ping_mock.assert_called_once_with( self._data_point, diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py index 9b4ae9be0d53..9f7df9a54b00 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py @@ -64,10 +64,7 @@ def test_enable_live_metrics(self, manager_mock): connection_string="test_cs", resource=mock_resource, ) - manager_mock.assert_called_with( - connection_string="test_cs", - resource=mock_resource - ) + manager_mock.assert_called_with(connection_string="test_cs", resource=mock_resource) class TestQuickpulseManager(unittest.TestCase): @@ -107,13 +104,9 @@ def test_init(self, generator_mock): self.assertEqual(qpm._base_monitoring_data_point.version, _get_sdk_version()) self.assertEqual(qpm._base_monitoring_data_point.invariant_version, 1) self.assertEqual( - qpm._base_monitoring_data_point.instance, - part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE, "") - ) - self.assertEqual( - qpm._base_monitoring_data_point.role_name, - part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE, "") + qpm._base_monitoring_data_point.instance, part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE, "") ) + self.assertEqual(qpm._base_monitoring_data_point.role_name, part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE, "")) self.assertEqual(qpm._base_monitoring_data_point.machine_name, platform.node()) self.assertEqual(qpm._base_monitoring_data_point.stream_id, "test_trace_id") self.assertTrue(isinstance(qpm._reader, _QuickpulseMetricReader)) @@ -145,7 +138,6 @@ def test_init(self, generator_mock): self.assertEqual(qpm._process_time_gauge.name, _PROCESS_TIME_NORMALIZED_NAME[0]) self.assertEqual(qpm._process_time_gauge._callbacks, [_get_process_time_normalized]) - def test_singleton(self): resource = Resource.create( { @@ -170,20 +162,14 @@ def test_singleton(self): ) self.assertEqual(qpm, qpm2) self.assertEqual( - qpm._base_monitoring_data_point.instance, - part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE, "") - ) - self.assertEqual( - qpm._base_monitoring_data_point.role_name, - part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE, "") + qpm._base_monitoring_data_point.instance, part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE, "") ) + self.assertEqual(qpm._base_monitoring_data_point.role_name, part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE, "")) self.assertEqual( - qpm2._base_monitoring_data_point.instance, - part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE, "") + qpm2._base_monitoring_data_point.instance, part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE, "") ) self.assertEqual( - qpm2._base_monitoring_data_point.role_name, - part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE, "") + qpm2._base_monitoring_data_point.role_name, part_a_fields.get(ContextTagKeys.AI_CLOUD_ROLE, "") ) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics._append_quickpulse_document") @@ -302,7 +288,7 @@ def test_record_log_exception(self, post_state_mock, log_doc_mock, append_doc_mo def test_process_memory(self): with mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.PROCESS") as process_mock: - memory = collections.namedtuple('memory', 'rss') + memory = collections.namedtuple("memory", "rss") pmem = memory(rss=40) process_mock.memory_info.return_value = pmem mem = _get_process_memory(None) @@ -311,7 +297,7 @@ def test_process_memory(self): def test_process_memory_error(self): with mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.PROCESS") as process_mock: - memory = collections.namedtuple('memory', 'rss') + memory = collections.namedtuple("memory", "rss") pmem = memory(rss=40) process_mock.memory_info.return_value = pmem process_mock.memory_info.side_effect = psutil.NoSuchProcess(1) @@ -324,7 +310,7 @@ def test_process_memory_error(self): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.PROCESS") def test_process_time(self, process_mock, process_time_mock, elapsed_time_mock): current = datetime.now() - cpu = collections.namedtuple("cpu", ['user', 'system']) + cpu = collections.namedtuple("cpu", ["user", "system"]) cpu_times = cpu(user=3.6, system=6.8) process_mock.cpu_times.return_value = cpu_times process_time_mock.return_value = 4.4 @@ -336,4 +322,5 @@ def test_process_time(self, process_mock, process_time_mock, elapsed_time_mock): num_cpus = psutil.cpu_count() self.assertAlmostEqual(obs.value, 1.2 / num_cpus, delta=1) + # cSpell:enable diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py index be863a70a24a..33f3027cf0d3 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py @@ -45,14 +45,12 @@ def test_get_redirect_location_no_header(self): policy = _QuickpulseRedirectPolicy() self.assertIsNone(policy.get_redirect_location(pipeline_resp_mock)) redirect_location = policy.get_redirect_location(pipeline_resp_mock) - + def test_get_redirect_location_invalid_url(self): policy = _QuickpulseRedirectPolicy() pipeline_resp_mock = mock.Mock() http_resp_mock = mock.Mock() - headers = { - "x-ms-qps-service-endpoint-redirect-v2": "invalid_url" - } + headers = {"x-ms-qps-service-endpoint-redirect-v2": "invalid_url"} http_resp_mock.headers = headers pipeline_resp_mock.http_response = http_resp_mock policy = _QuickpulseRedirectPolicy() @@ -64,7 +62,7 @@ def test_get_redirect_location_invalid_url(self): policy._qp_client_ref = qp_client_ref redirect_location = policy.get_redirect_location(pipeline_resp_mock) self.assertEqual(redirect_location, "invalid_url") - self.assertEqual(client_mock._base_url,"previous_url") + self.assertEqual(client_mock._base_url, "previous_url") def test_get_redirect_location_no_client(self): policy = _QuickpulseRedirectPolicy() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py index c75156bc4ce5..33d0c2e6990a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py @@ -49,8 +49,8 @@ def test_metric_to_qp_data_point_hist(self, datetime_mock): 0, 2, 10, - [1,1,0], - [0,10,20], + [1, 1, 0], + [0, 10, 20], 0, 5, ) @@ -63,11 +63,7 @@ def test_metric_to_qp_data_point_hist(self, datetime_mock): resource_metric.scope_metrics = [scope_metric] metric_data = mock.Mock() metric_data.resource_metrics = [resource_metric] - metric_point = MetricPoint( - name=_COMMITTED_BYTES_NAME[1], - weight=1, - value=5 - ) + metric_point = MetricPoint(name=_COMMITTED_BYTES_NAME[1], weight=1, value=5) documents = [mock.Mock()] date_now = datetime.now() datetime_mock.now.return_value = date_now @@ -98,11 +94,7 @@ def test_metric_to_qp_data_point_num(self, datetime_mock): resource_metric.scope_metrics = [scope_metric] metric_data = mock.Mock() metric_data.resource_metrics = [resource_metric] - metric_point = MetricPoint( - name=_COMMITTED_BYTES_NAME[1], - weight=1, - value=7 - ) + metric_point = MetricPoint(name=_COMMITTED_BYTES_NAME[1], weight=1, value=7) documents = [mock.Mock()] date_now = datetime.now() datetime_mock.now.return_value = date_now diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_exporter.py index 593cf2371636..880d597724ba 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_exporter.py @@ -40,7 +40,7 @@ def clean_folder(folder): elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: - print('Failed to delete %s. Reason: %s' % (file_path, e)) + print("Failed to delete %s. Reason: %s" % (file_path, e)) # pylint: disable=protected-access @@ -48,25 +48,22 @@ class TestStatsbeatExporter(unittest.TestCase): @classmethod def setUpClass(cls): os.environ.clear() - os.environ[ - "APPINSIGHTS_INSTRUMENTATIONKEY" - ] = "1234abcd-5678-4efa-8abc-1234567890ab" + os.environ["APPINSIGHTS_INSTRUMENTATIONKEY"] = "1234abcd-5678-4efa-8abc-1234567890ab" os.environ["APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL"] = "false" cls._exporter = _StatsBeatExporter( disable_offline_storage=True, ) cls._envelopes_to_export = [TelemetryItem(name="Test", time=datetime.now())] - @mock.patch( - 'azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics') + @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_init(self, collect_mock): exporter = _StatsBeatExporter(disable_offline_storage=True) self.assertFalse(exporter._should_collect_stats()) collect_mock.assert_not_called() def test_point_to_envelope(self): - resource = Resource.create(attributes={"asd":"test_resource"}) - point=NumberDataPoint( + resource = Resource.create(attributes={"asd": "test_resource"}) + point = NumberDataPoint( start_time_unix_nano=1646865018558419456, time_unix_nano=1646865018558419457, value=10, @@ -75,10 +72,10 @@ def test_point_to_envelope(self): for ot_name, sb_name in _STATSBEAT_METRIC_NAME_MAPPINGS.items(): envelope = self._exporter._point_to_envelope(point, ot_name, resource) self.assertEqual(envelope.data.base_data.metrics[0].name, sb_name) - + def test_transmit_200_reach_ingestion(self): _STATSBEAT_STATE["INITIAL_SUCCESS"] = False - with mock.patch.object(AzureMonitorClient, 'track') as post: + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=1, items_accepted=1, @@ -90,17 +87,11 @@ def test_transmit_200_reach_ingestion(self): def test_transmit_206_reach_ingestion(self): _STATSBEAT_STATE["INITIAL_SUCCESS"] = False - with mock.patch.object(AzureMonitorClient, 'track') as post: + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=3, items_accepted=1, - errors=[ - TelemetryErrorDetails( - index=0, - status_code=500, - message="should retry" - ) - ], + errors=[TelemetryErrorDetails(index=0, status_code=500, message="should retry")], ) result = self._exporter._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @@ -108,11 +99,12 @@ def test_transmit_206_reach_ingestion(self): def test_transmit_reach_ingestion_code(self): _STATSBEAT_STATE["INITIAL_SUCCESS"] = False - with mock.patch("azure.monitor.opentelemetry.exporter.export._base._reached_ingestion_code") as m, \ - mock.patch("azure.monitor.opentelemetry.exporter.export._base._is_retryable_code") as p: + with mock.patch("azure.monitor.opentelemetry.exporter.export._base._reached_ingestion_code") as m, mock.patch( + "azure.monitor.opentelemetry.exporter.export._base._is_retryable_code" + ) as p: m.return_value = True p.return_value = True - with mock.patch.object(AzureMonitorClient, 'track', throw(HttpResponseError)): + with mock.patch.object(AzureMonitorClient, "track", throw(HttpResponseError)): result = self._exporter._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_RETRYABLE) self.assertTrue(_STATSBEAT_STATE["INITIAL_SUCCESS"]) @@ -120,11 +112,12 @@ def test_transmit_reach_ingestion_code(self): def test_transmit_not_reach_ingestion_code(self): _STATSBEAT_STATE["INITIAL_SUCCESS"] = False _STATSBEAT_STATE["INITIAL_FAILURE_COUNT"] = 1 - with mock.patch("azure.monitor.opentelemetry.exporter.export._base._reached_ingestion_code") as m, \ - mock.patch("azure.monitor.opentelemetry.exporter.export._base._is_retryable_code") as p: + with mock.patch("azure.monitor.opentelemetry.exporter.export._base._reached_ingestion_code") as m, mock.patch( + "azure.monitor.opentelemetry.exporter.export._base._is_retryable_code" + ) as p: m.return_value = False p.return_value = False - with mock.patch.object(AzureMonitorClient, 'track', throw(HttpResponseError)): + with mock.patch.object(AzureMonitorClient, "track", throw(HttpResponseError)): result = self._exporter._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) self.assertFalse(_STATSBEAT_STATE["INITIAL_SUCCESS"]) @@ -134,7 +127,7 @@ def test_transmit_not_reach_ingestion_exception(self): _STATSBEAT_STATE["INITIAL_SUCCESS"] = False _STATSBEAT_STATE["INITIAL_FAILURE_COUNT"] = 1 with mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.shutdown_statsbeat_metrics") as m: - with mock.patch.object(AzureMonitorClient, 'track', throw(Exception)): + with mock.patch.object(AzureMonitorClient, "track", throw(Exception)): result = self._exporter._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) self.assertFalse(_STATSBEAT_STATE["INITIAL_SUCCESS"]) @@ -145,7 +138,7 @@ def test_transmit_not_reach_ingestion_exception_shutdown(self): _STATSBEAT_STATE["INITIAL_SUCCESS"] = False _STATSBEAT_STATE["INITIAL_FAILURE_COUNT"] = 2 with mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.shutdown_statsbeat_metrics") as m: - with mock.patch.object(AzureMonitorClient, 'track', throw(Exception)): + with mock.patch.object(AzureMonitorClient, "track", throw(Exception)): result = self._exporter._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) self.assertFalse(_STATSBEAT_STATE["INITIAL_SUCCESS"]) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py index b3397c6abea0..ef622bcd39e4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py @@ -46,6 +46,7 @@ _RP_Names, ) + class MockResponse(object): def __init__(self, status_code, text): self.status_code = status_code @@ -61,21 +62,17 @@ def func(*_args, **_kwargs): # cSpell:disable + # pylint: disable=protected-access class TestStatsbeat(unittest.TestCase): def setUp(self): _statsbeat._STATSBEAT_METRICS = None _STATSBEAT_STATE["SHUTDOWN"] = False - @mock.patch.object(MeterProvider, 'shutdown') - @mock.patch.object(MeterProvider, 'force_flush') - @mock.patch.object(_StatsbeatMetrics, 'init_non_initial_metrics') - def test_collect_statsbeat_metrics( - self, - non_init_mock, - flush_mock, - shutdown_mock - ): + @mock.patch.object(MeterProvider, "shutdown") + @mock.patch.object(MeterProvider, "force_flush") + @mock.patch.object(_StatsbeatMetrics, "init_non_initial_metrics") + def test_collect_statsbeat_metrics(self, non_init_mock, flush_mock, shutdown_mock): exporter = mock.Mock() exporter._endpoint = "test endpoint" exporter._instrumentation_key = "test ikey" @@ -100,70 +97,59 @@ def test_collect_statsbeat_metrics_exists(self): _statsbeat.collect_statsbeat_metrics(exporter) self.assertEqual(_statsbeat._STATSBEAT_METRICS, mock_metrics) - @mock.patch.object(MeterProvider, 'shutdown') - @mock.patch.object(MeterProvider, 'force_flush') - @mock.patch.object(_StatsbeatMetrics, 'init_non_initial_metrics') - def test_collect_statsbeat_metrics_non_eu( - self, - non_init_mock, - flush_mock, - shutdown_mock - ): + @mock.patch.object(MeterProvider, "shutdown") + @mock.patch.object(MeterProvider, "force_flush") + @mock.patch.object(_StatsbeatMetrics, "init_non_initial_metrics") + def test_collect_statsbeat_metrics_non_eu(self, non_init_mock, flush_mock, shutdown_mock): exporter = mock.Mock() exporter._instrumentation_key = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3333" exporter._endpoint = "https://westus-0.in.applicationinsights.azure.com/" self.assertIsNone(_statsbeat._STATSBEAT_METRICS) with mock.patch.dict( - os.environ, { + os.environ, + { _APPLICATIONINSIGHTS_STATS_CONNECTION_STRING_ENV_NAME: "", - }): + }, + ): _statsbeat.collect_statsbeat_metrics(exporter) self.assertIsNotNone(_statsbeat._STATSBEAT_METRICS) mp = _statsbeat._STATSBEAT_METRICS._meter_provider mr = mp._sdk_config.metric_readers[0] stats_exporter = mr._exporter self.assertEqual( - stats_exporter._instrumentation_key, - _DEFAULT_NON_EU_STATS_CONNECTION_STRING.split(";")[0].split("=")[1] + stats_exporter._instrumentation_key, _DEFAULT_NON_EU_STATS_CONNECTION_STRING.split(";")[0].split("=")[1] ) self.assertEqual( - stats_exporter._endpoint, - _DEFAULT_NON_EU_STATS_CONNECTION_STRING.split(";")[1].split("=")[1] # noqa: E501 + stats_exporter._endpoint, _DEFAULT_NON_EU_STATS_CONNECTION_STRING.split(";")[1].split("=")[1] # noqa: E501 ) - @mock.patch.object(MeterProvider, 'shutdown') - @mock.patch.object(MeterProvider, 'force_flush') - @mock.patch.object(_StatsbeatMetrics, 'init_non_initial_metrics') - def test_collect_statsbeat_metrics_eu( - self, - non_init_mock, - flush_mock, - shutdown_mock - ): + @mock.patch.object(MeterProvider, "shutdown") + @mock.patch.object(MeterProvider, "force_flush") + @mock.patch.object(_StatsbeatMetrics, "init_non_initial_metrics") + def test_collect_statsbeat_metrics_eu(self, non_init_mock, flush_mock, shutdown_mock): exporter = mock.Mock() exporter._instrumentation_key = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3333" exporter._endpoint = "https://northeurope-0.in.applicationinsights.azure.com/" self.assertIsNone(_statsbeat._STATSBEAT_METRICS) with mock.patch.dict( - os.environ, { + os.environ, + { _APPLICATIONINSIGHTS_STATS_CONNECTION_STRING_ENV_NAME: "", - }): + }, + ): _statsbeat.collect_statsbeat_metrics(exporter) self.assertIsNotNone(_statsbeat._STATSBEAT_METRICS) mp = _statsbeat._STATSBEAT_METRICS._meter_provider mr = mp._sdk_config.metric_readers[0] stats_exporter = mr._exporter self.assertEqual( - stats_exporter._instrumentation_key, - _DEFAULT_EU_STATS_CONNECTION_STRING.split(";")[0].split("=")[1] + stats_exporter._instrumentation_key, _DEFAULT_EU_STATS_CONNECTION_STRING.split(";")[0].split("=")[1] ) self.assertEqual( - stats_exporter._endpoint, - _DEFAULT_EU_STATS_CONNECTION_STRING.split(";")[1].split("=")[1] # noqa: E501 + stats_exporter._endpoint, _DEFAULT_EU_STATS_CONNECTION_STRING.split(";")[1].split("=")[1] # noqa: E501 ) - - @mock.patch('azure.monitor.opentelemetry.exporter.statsbeat._statsbeat._StatsbeatMetrics') + @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat._StatsbeatMetrics") @mock.patch.dict( "os.environ", { @@ -195,8 +181,7 @@ def test_collect_statsbeat_metrics_aad( "", ) - - @mock.patch('azure.monitor.opentelemetry.exporter.statsbeat._statsbeat._StatsbeatMetrics') + @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat._StatsbeatMetrics") @mock.patch.dict( "os.environ", { @@ -228,7 +213,7 @@ def test_collect_statsbeat_metrics_no_aad( "", ) - @mock.patch('azure.monitor.opentelemetry.exporter.statsbeat._statsbeat._StatsbeatMetrics') + @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat._StatsbeatMetrics") @mock.patch.dict( "os.environ", { @@ -272,18 +257,10 @@ def test_shutdown_statsbeat_metrics(self): self.assertTrue(_STATSBEAT_STATE["SHUTDOWN"]) -_StatsbeatMetrics_COMMON_ATTRS = dict( - _StatsbeatMetrics._COMMON_ATTRIBUTES -) -_StatsbeatMetrics_NETWORK_ATTRS = dict( - _StatsbeatMetrics._NETWORK_ATTRIBUTES -) -_StatsbeatMetrics_FEATURE_ATTRIBUTES = dict( - _StatsbeatMetrics._FEATURE_ATTRIBUTES -) -_StatsbeatMetrics_INSTRUMENTATION_ATTRIBUTES = dict( - _StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES -) +_StatsbeatMetrics_COMMON_ATTRS = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) +_StatsbeatMetrics_NETWORK_ATTRS = dict(_StatsbeatMetrics._NETWORK_ATTRIBUTES) +_StatsbeatMetrics_FEATURE_ATTRIBUTES = dict(_StatsbeatMetrics._FEATURE_ATTRIBUTES) +_StatsbeatMetrics_INSTRUMENTATION_ATTRIBUTES = dict(_StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES) # pylint: disable=protected-access @@ -305,18 +282,10 @@ def setUpClass(cls): def setUp(self): _statsbeat._STATSBEAT_METRICS = None - _StatsbeatMetrics._COMMON_ATTRIBUTES = dict( - _StatsbeatMetrics_COMMON_ATTRS - ) - _StatsbeatMetrics._NETWORK_ATTRIBUTES = dict( - _StatsbeatMetrics_NETWORK_ATTRS - ) - _StatsbeatMetrics._FEATURE_ATTRIBUTES = dict( - _StatsbeatMetrics_FEATURE_ATTRIBUTES - ) - _StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES = dict( - _StatsbeatMetrics_INSTRUMENTATION_ATTRIBUTES - ) + _StatsbeatMetrics._COMMON_ATTRIBUTES = dict(_StatsbeatMetrics_COMMON_ATTRS) + _StatsbeatMetrics._NETWORK_ATTRIBUTES = dict(_StatsbeatMetrics_NETWORK_ATTRS) + _StatsbeatMetrics._FEATURE_ATTRIBUTES = dict(_StatsbeatMetrics_FEATURE_ATTRIBUTES) + _StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES = dict(_StatsbeatMetrics_INSTRUMENTATION_ATTRIBUTES) _REQUESTS_MAP.clear() _STATSBEAT_STATE["INITIAL_FAILURE_COUNT"] = 0 _STATSBEAT_STATE["INITIAL_SUCCESS"] = False @@ -324,7 +293,6 @@ def setUp(self): _STATSBEAT_STATE["CUSTOM_EVENTS_FEATURE_SET"] = False _STATSBEAT_STATE["LIVE_METRICS_FEATURE_SET"] = False - def test_statsbeat_metric_init(self): mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" @@ -434,9 +402,12 @@ def test_get_attach_metric_does_not_meet_threshold(self): { "WEBSITE_SITE_NAME": "site_name", "WEBSITE_HOME_STAMPNAME": "stamp_name", - } + }, + ) + @mock.patch( + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", + return_value=False, ) - @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", return_value=False) def test_get_attach_metric_appsvc(self, metadata_mock): attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) self.assertEqual(attributes["rp"], _RP_Names.UNKNOWN.value) @@ -454,9 +425,12 @@ def test_get_attach_metric_appsvc(self, metadata_mock): { "FUNCTIONS_WORKER_RUNTIME": "runtime", "WEBSITE_HOSTNAME": "host_name", - } + }, + ) + @mock.patch( + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", + return_value=False, ) - @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", return_value=False) def test_get_attach_metric_functions(self, metadata_mock): attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) self.assertEqual(attributes["rp"], _RP_Names.UNKNOWN.value) @@ -473,7 +447,7 @@ def test_get_attach_metric_functions(self, metadata_mock): os.environ, { "AKS_ARM_NAMESPACE_ID": "namespace_id", - } + }, ) def test_get_attach_metric_aks(self): attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) @@ -486,7 +460,9 @@ def test_get_attach_metric_aks(self): self.assertEqual(obs.attributes, attributes) self.assertEqual(_StatsbeatMetrics._COMMON_ATTRIBUTES["rp"], _RP_Names.AKS.value) - @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata") + @mock.patch( + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata" + ) def test_get_attach_metric_vm(self, metadata_mock): mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" @@ -519,7 +495,10 @@ def test_get_attach_metric_vm(self, metadata_mock): self.assertEqual(_StatsbeatMetrics._COMMON_ATTRIBUTES["rp"], _RP_Names.VM.value) self.assertEqual(_StatsbeatMetrics._COMMON_ATTRIBUTES["os"], "test_os") - @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", return_value=False) + @mock.patch( + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", + return_value=False, + ) def test_get_attach_metric_vm_no_os(self, metadata_mock): mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" @@ -578,17 +557,8 @@ def test_get_azure_compute_metadata(self): 0, False, ) - with mock.patch('requests.get') as get: - get.return_value = MockResponse( - 200, - json.dumps( - { - 'vmId': 5, - 'subscriptionId': 3, - 'osType': 'Linux' - } - ) - ) + with mock.patch("requests.get") as get: + get.return_value = MockResponse(200, json.dumps({"vmId": 5, "subscriptionId": 3, "osType": "Linux"})) vm_result = metric._get_azure_compute_metadata() self.assertTrue(vm_result) self.assertEqual(metric._vm_data["vmId"], 5) @@ -608,10 +578,7 @@ def test_get_azure_compute_metadata_not_vm(self): 0, False, ) - with mock.patch( - 'requests.get', - throw(requests.exceptions.ConnectionError) - ): + with mock.patch("requests.get", throw(requests.exceptions.ConnectionError)): vm_result = metric._get_azure_compute_metadata() self.assertFalse(vm_result) self.assertEqual(len(metric._vm_data), 0) @@ -629,10 +596,7 @@ def test_get_azure_compute_metadata_not_vm_timeout(self): 0, False, ) - with mock.patch( - 'requests.get', - throw(requests.Timeout) - ): + with mock.patch("requests.get", throw(requests.Timeout)): vm_result = metric._get_azure_compute_metadata() self.assertFalse(vm_result) self.assertEqual(len(metric._vm_data), 0) @@ -650,10 +614,7 @@ def test_get_azure_compute_metadata_vm_retry(self): 0, False, ) - with mock.patch( - 'requests.get', - throw(requests.exceptions.RequestException) - ): + with mock.patch("requests.get", throw(requests.exceptions.RequestException)): vm_result = metric._get_azure_compute_metadata() self.assertFalse(vm_result) self.assertEqual(len(metric._vm_data), 0) @@ -740,21 +701,16 @@ def test_get_feature_metric_aad(self): mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" - metric = _StatsbeatMetrics( - mp, - ikey, - endpoint, - True, - 0, - True - ) + metric = _StatsbeatMetrics(mp, ikey, endpoint, True, 0, True) self.assertEqual(_StatsbeatMetrics._FEATURE_ATTRIBUTES["feature"], _StatsbeatFeature.AAD) observations = metric._get_feature_metric(options=None) self.assertEqual(len(observations), 1) self.assertEqual(_StatsbeatMetrics._FEATURE_ATTRIBUTES["feature"], _StatsbeatFeature.AAD) # pylint: disable=protected-access - @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics.get_statsbeat_custom_events_feature_set") + @mock.patch( + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics.get_statsbeat_custom_events_feature_set" + ) def test_get_feature_metric_custom_events(self, feature_mock): feature_mock.return_value = True mp = MeterProvider() @@ -777,9 +733,10 @@ def test_get_feature_metric_custom_events(self, feature_mock): self.assertEqual(obs.value, 1) self.assertEqual(obs.attributes, attributes) - # pylint: disable=protected-access - @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics.get_statsbeat_live_metrics_feature_set") + @mock.patch( + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics.get_statsbeat_live_metrics_feature_set" + ) def test_get_feature_metric_live_metrics(self, feature_mock): feature_mock.return_value = True mp = MeterProvider() @@ -809,15 +766,7 @@ def test_get_feature_metric_distro(self): mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" - metric = _StatsbeatMetrics( - mp, - ikey, - endpoint, - True, - 0, - False, - "1.0.0" - ) + metric = _StatsbeatMetrics(mp, ikey, endpoint, True, 0, False, "1.0.0") self.assertEqual(_StatsbeatMetrics._FEATURE_ATTRIBUTES["feature"], _StatsbeatFeature.DISTRO) observations = metric._get_feature_metric(options=None) self.assertEqual(len(observations), 1) @@ -841,9 +790,7 @@ def test_get_feature_metric_instrumentation(self): attributes.update(_StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES) self.assertEqual(attributes["type"], _FEATURE_TYPES.INSTRUMENTATION) self.assertEqual(attributes["feature"], 0) - with mock.patch( - "azure.monitor.opentelemetry.exporter._utils.get_instrumentations" - ) as instrumentations: + with mock.patch("azure.monitor.opentelemetry.exporter._utils.get_instrumentations") as instrumentations: instrumentations.return_value = 1026 observations = metric._get_feature_metric(options=None) self.assertEqual( @@ -871,9 +818,7 @@ def test_get_feature_metric_instrumentation_none(self): ) metric._feature = _StatsbeatFeature.NONE self.assertEqual(_StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES["feature"], 0) - with mock.patch( - "azure.monitor.opentelemetry.exporter._utils.get_instrumentations" - ) as instrumentations: + with mock.patch("azure.monitor.opentelemetry.exporter._utils.get_instrumentations") as instrumentations: instrumentations.return_value = 0 observations = metric._get_feature_metric(options=None) self.assertEqual(len(observations), 0) @@ -904,7 +849,7 @@ def test_init_non_initial_metrics(self): self.assertEqual(metric._throttle_count.name, _REQ_THROTTLE_NAME[0]) self.assertEqual(metric._exception_count.name, _REQ_EXCEPTION_NAME[0]) self.assertEqual(metric._average_duration.name, _REQ_DURATION_NAME[0]) - + def test_get_success_count(self): mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" @@ -1076,4 +1021,5 @@ def test_shorten_host(self): url = "http://fakehost-5/" self.assertEqual(_shorten_host(url), "fakehost-5") + # cSpell:enable diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_exporter.py index e282e44c7cb3..9804457d7bda 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_exporter.py @@ -63,7 +63,7 @@ def clean_folder(folder): elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: - print('Failed to delete %s. Reason: %s' % (file_path, e)) + print("Failed to delete %s. Reason: %s" % (file_path, e)) # pylint: disable=W0212 @@ -71,9 +71,7 @@ def clean_folder(folder): class TestBaseExporter(unittest.TestCase): @classmethod def setUpClass(cls): - os.environ[ - "APPINSIGHTS_INSTRUMENTATIONKEY" - ] = "1234abcd-5678-4efa-8abc-1234567890ab" + os.environ["APPINSIGHTS_INSTRUMENTATIONKEY"] = "1234abcd-5678-4efa-8abc-1234567890ab" os.environ["APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL"] = "true" cls._base = BaseExporter() cls._envelopes_to_export = [TelemetryItem(name="Test", time=datetime.now())] @@ -156,8 +154,10 @@ def test_constructor_no_storage_directory(self, mock_get_temp_dir): self.assertEqual( base._storage_directory, os.path.join( - TEST_TEMP_DIR, "Microsoft/AzureMonitor", "opentelemetry-python-" + "4321abcd-5678-4efa-8abc-1234567890ab" - ) + TEST_TEMP_DIR, + "Microsoft/AzureMonitor", + "opentelemetry-python-" + "4321abcd-5678-4efa-8abc-1234567890ab", + ), ) mock_get_temp_dir.assert_called_once() @@ -229,12 +229,12 @@ def test_transmit_from_storage_success(self, dict_patch, format_patch): exporter.storage = mock.Mock() blob_mock = mock.Mock() blob_mock.lease.return_value = True - envelope_mock = {"name":"test","time":"time"} + envelope_mock = {"name": "test", "time": "time"} blob_mock.get.return_value = [envelope_mock] - dict_patch.return_value = {"name":"test","time":"time"} + dict_patch.return_value = {"name": "test", "time": "time"} format_patch.return_value = envelope_mock exporter.storage.gets.return_value = [blob_mock] - with mock.patch.object(AzureMonitorClient, 'track') as post: + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=1, items_accepted=1, @@ -252,13 +252,13 @@ def test_transmit_from_storage_store_again(self, dict_patch, format_patch): exporter.storage = mock.Mock() blob_mock = mock.Mock() blob_mock.lease.return_value = True - envelope_mock = {"name":"test","time":"time"} + envelope_mock = {"name": "test", "time": "time"} blob_mock.get.return_value = [envelope_mock] - dict_patch.return_value = {"name":"test","time":"time"} + dict_patch.return_value = {"name": "test", "time": "time"} format_patch.return_value = envelope_mock exporter.storage.gets.return_value = [blob_mock] with mock.patch("azure.monitor.opentelemetry.exporter.export._base._is_retryable_code"): - with mock.patch.object(AzureMonitorClient, 'track', throw(HttpResponseError)): + with mock.patch.object(AzureMonitorClient, "track", throw(HttpResponseError)): exporter._transmit_from_storage() exporter.storage.gets.assert_called_once() blob_mock.lease.assert_called() @@ -279,11 +279,8 @@ def test_transmit_from_storage_lease_failure(self): blob_mock.delete.assert_not_called() def test_format_storage_telemetry_item(self): - time=datetime.now() - base = MonitorBase( - base_type="", - base_data=None - ) + time = datetime.now() + base = MonitorBase(base_type="", base_data=None) ti = TelemetryItem( name="test_telemetry_item", time=time, @@ -292,7 +289,7 @@ def test_format_storage_telemetry_item(self): sequence="test_sequence", instrumentation_key="4321abcd-5678-4efa-8abc-1234567890ab", tags={"tag1": "val1", "tag2": "val2"}, - data=base + data=base, ) # MessageData message_data = MessageData( @@ -339,10 +336,7 @@ def test_format_storage_telemetry_item(self): stack="Traceback \n", ) exc_data = TelemetryExceptionData( - version=2, - properties={"key1": "val1"}, - severity_level="3", - exceptions=[exc_data_details] + version=2, properties={"key1": "val1"}, severity_level="3", exceptions=[exc_data_details] ) base.base_type = "ExceptionData" self.assertEqual(_MONITOR_DOMAIN_MAPPING.get(base.base_type), TelemetryExceptionData) @@ -457,26 +451,26 @@ def test_format_storage_telemetry_item(self): def test_transmit_http_error_retryable(self): with mock.patch("azure.monitor.opentelemetry.exporter.export._base._is_retryable_code") as m: m.return_value = True - with mock.patch.object(AzureMonitorClient, 'track', throw(HttpResponseError)): + with mock.patch.object(AzureMonitorClient, "track", throw(HttpResponseError)): result = self._base._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_RETRYABLE) def test_transmit_http_error_not_retryable(self): with mock.patch("azure.monitor.opentelemetry.exporter.export._base._is_retryable_code") as m: m.return_value = False - with mock.patch.object(AzureMonitorClient, 'track', throw(HttpResponseError)): + with mock.patch.object(AzureMonitorClient, "track", throw(HttpResponseError)): result = self._base._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) def test_transmit_http_error_redirect(self): response = HttpResponse(None, None) response.status_code = 307 - response.headers = {"location":"https://example.com"} + response.headers = {"location": "https://example.com"} prev_redirects = self._base.client._config.redirect_policy.max_redirects self._base.client._config.redirect_policy.max_redirects = 2 prev_host = self._base.client._config.host error = HttpResponseError(response=response) - with mock.patch.object(AzureMonitorClient, 'track') as post: + with mock.patch.object(AzureMonitorClient, "track") as post: post.side_effect = error result = self._base._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @@ -491,7 +485,7 @@ def test_transmit_http_error_redirect_missing_headers(self): response.headers = None error = HttpResponseError(response=response) prev_host = self._base.client._config.host - with mock.patch.object(AzureMonitorClient, 'track') as post: + with mock.patch.object(AzureMonitorClient, "track") as post: post.side_effect = error result = self._base._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @@ -501,10 +495,10 @@ def test_transmit_http_error_redirect_missing_headers(self): def test_transmit_http_error_redirect_invalid_location_header(self): response = HttpResponse(None, None) response.status_code = 307 - response.headers = {"location":"123"} + response.headers = {"location": "123"} error = HttpResponseError(response=response) prev_host = self._base.client._config.host - with mock.patch.object(AzureMonitorClient, 'track') as post: + with mock.patch.object(AzureMonitorClient, "track") as post: post.side_effect = error result = self._base._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @@ -512,20 +506,20 @@ def test_transmit_http_error_redirect_invalid_location_header(self): self.assertEqual(self._base.client._config.host, prev_host) def test_transmit_request_error(self): - with mock.patch.object(AzureMonitorClient, 'track', throw(ServiceRequestError, message="error")): + with mock.patch.object(AzureMonitorClient, "track", throw(ServiceRequestError, message="error")): result = self._base._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_transmit_request_error_statsbeat(self, stats_mock): exporter = BaseExporter(disable_offline_storage=True) - with mock.patch.object(AzureMonitorClient, 'track', throw(ServiceRequestError, message="error")): + with mock.patch.object(AzureMonitorClient, "track", throw(ServiceRequestError, message="error")): result = exporter._transmit(self._envelopes_to_export) stats_mock.assert_called_once() self.assertEqual(len(_REQUESTS_MAP), 3) @@ -535,20 +529,20 @@ def test_transmit_request_error_statsbeat(self, stats_mock): self.assertEqual(result, ExportResult.FAILED_RETRYABLE) def test_transmit_request_exception(self): - with mock.patch.object(AzureMonitorClient, 'track', throw(Exception)): + with mock.patch.object(AzureMonitorClient, "track", throw(Exception)): result = self._base._transmit(self._envelopes_to_export) self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_transmit_request_exception_statsbeat(self, stats_mock): exporter = BaseExporter(disable_offline_storage=True) - with mock.patch.object(AzureMonitorClient, 'track', throw(Exception)): + with mock.patch.object(AzureMonitorClient, "track", throw(Exception)): result = exporter._transmit(self._envelopes_to_export) stats_mock.assert_called_once() self.assertEqual(len(_REQUESTS_MAP), 3) @@ -558,7 +552,7 @@ def test_transmit_request_exception_statsbeat(self, stats_mock): self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) def test_transmission_200(self): - with mock.patch.object(AzureMonitorClient, 'track') as post: + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=1, items_accepted=1, @@ -570,13 +564,13 @@ def test_transmission_200(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_200(self, stats_mock): exporter = BaseExporter(disable_offline_storage=True) - with mock.patch.object(AzureMonitorClient, 'track') as post: + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=1, items_accepted=1, @@ -594,9 +588,12 @@ def test_transmission_206_retry(self): exporter = BaseExporter(disable_offline_storage=True) exporter.storage = mock.Mock() test_envelope = TelemetryItem(name="testEnvelope", time=datetime.now()) - custom_envelopes_to_export = [TelemetryItem(name="Test", time=datetime.now( - )), TelemetryItem(name="Test", time=datetime.now()), test_envelope] - with mock.patch.object(AzureMonitorClient, 'track') as post: + custom_envelopes_to_export = [ + TelemetryItem(name="Test", time=datetime.now()), + TelemetryItem(name="Test", time=datetime.now()), + test_envelope, + ] + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=3, items_accepted=1, @@ -606,11 +603,7 @@ def test_transmission_206_retry(self): status_code=400, message="should drop", ), - TelemetryErrorDetails( - index=2, - status_code=500, - message="should retry" - ) + TelemetryErrorDetails(index=2, status_code=500, message="should retry"), ], ) result = exporter._transmit(custom_envelopes_to_export) @@ -620,17 +613,20 @@ def test_transmission_206_retry(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_206_retry(self, stats_mock): exporter = BaseExporter(disable_offline_storage=True) exporter.storage = mock.Mock() test_envelope = TelemetryItem(name="testEnvelope", time=datetime.now()) - custom_envelopes_to_export = [TelemetryItem(name="Test", time=datetime.now( - )), TelemetryItem(name="Test", time=datetime.now()), test_envelope] - with mock.patch.object(AzureMonitorClient, 'track') as post: + custom_envelopes_to_export = [ + TelemetryItem(name="Test", time=datetime.now()), + TelemetryItem(name="Test", time=datetime.now()), + test_envelope, + ] + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=3, items_accepted=1, @@ -640,11 +636,7 @@ def test_statsbeat_206_retry(self, stats_mock): status_code=400, message="should drop", ), - TelemetryErrorDetails( - index=2, - status_code=500, - message="should retry" - ) + TelemetryErrorDetails(index=2, status_code=500, message="should retry"), ], ) result = exporter._transmit(custom_envelopes_to_export) @@ -659,9 +651,12 @@ def test_transmission_206_no_retry(self): exporter = BaseExporter(disable_offline_storage=True) exporter.storage = mock.Mock() test_envelope = TelemetryItem(name="testEnvelope", time=datetime.now()) - custom_envelopes_to_export = [TelemetryItem(name="Test", time=datetime.now( - )), TelemetryItem(name="Test", time=datetime.now()), test_envelope] - with mock.patch.object(AzureMonitorClient, 'track') as post: + custom_envelopes_to_export = [ + TelemetryItem(name="Test", time=datetime.now()), + TelemetryItem(name="Test", time=datetime.now()), + test_envelope, + ] + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=3, items_accepted=2, @@ -680,17 +675,20 @@ def test_transmission_206_no_retry(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_206_no_retry(self, stats_mock): exporter = BaseExporter(disable_offline_storage=True) exporter.storage = mock.Mock() test_envelope = TelemetryItem(name="testEnvelope", time=datetime.now()) - custom_envelopes_to_export = [TelemetryItem(name="Test", time=datetime.now( - )), TelemetryItem(name="Test", time=datetime.now()), test_envelope] - with mock.patch.object(AzureMonitorClient, 'track') as post: + custom_envelopes_to_export = [ + TelemetryItem(name="Test", time=datetime.now()), + TelemetryItem(name="Test", time=datetime.now()), + test_envelope, + ] + with mock.patch.object(AzureMonitorClient, "track") as post: post.return_value = TrackResponse( items_received=3, items_accepted=2, @@ -718,8 +716,8 @@ def test_transmission_400(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.shutdown_statsbeat_metrics") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") @@ -745,8 +743,8 @@ def test_transmission_402(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_402(self, stats_mock): @@ -770,8 +768,8 @@ def test_transmission_408(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_408(self, stats_mock): @@ -795,8 +793,8 @@ def test_transmission_429(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_429(self, stats_mock): @@ -820,8 +818,8 @@ def test_transmission_439(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_439(self, stats_mock): @@ -845,8 +843,8 @@ def test_transmission_500(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_500(self, stats_mock): @@ -870,8 +868,8 @@ def test_transmission_502(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_502(self, stats_mock): @@ -895,8 +893,8 @@ def test_transmission_503(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) def test_statsbeat_503(self): with mock.patch("requests.Session.request") as post: @@ -917,8 +915,8 @@ def test_transmission_504(self): @mock.patch.dict( os.environ, { - "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", - } + "APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL": "false", + }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") def test_statsbeat_504(self, stats_mock): @@ -945,39 +943,43 @@ def test_exporter_credential(self, mock_add_credential_policy): mock_add_credential_policy.assert_called_once_with(TEST_CREDENTIAL, TEST_AUTH_POLICY) def test_get_auth_policy(self): - class TestCredential(): + class TestCredential: def get_token(): return "TEST_TOKEN" + credential = TestCredential() result = _get_auth_policy(credential, TEST_AUTH_POLICY) self.assertEqual(result._credential, credential) - def test_get_auth_policy_no_credential(self): self.assertEqual(_get_auth_policy(credential=None, default_auth_policy=TEST_AUTH_POLICY), TEST_AUTH_POLICY) - def test_get_auth_policy_invalid_credential(self): - class InvalidTestCredential(): + class InvalidTestCredential: def invalid_get_token(): return "TEST_TOKEN" - self.assertRaises(ValueError, _get_auth_policy, credential=InvalidTestCredential(), default_auth_policy=TEST_AUTH_POLICY) + + self.assertRaises( + ValueError, _get_auth_policy, credential=InvalidTestCredential(), default_auth_policy=TEST_AUTH_POLICY + ) def validate_telemetry_item(item1, item2): - return item1.name == item2.name and \ - item1.time.year == item2.time.year and \ - item1.time.month == item2.time.month and \ - item1.time.day == item2.time.day and \ - item1.time.hour == item2.time.hour and \ - item1.time.minute == item2.time.minute and \ - item1.time.second == item2.time.second and \ - item1.time.microsecond == item2.time.microsecond and \ - item1.version == item2.version and \ - item1.sample_rate == item2.sample_rate and \ - item1.sequence == item2.sequence and \ - item1.instrumentation_key == item2.instrumentation_key and \ - item1.tags == item2.tags + return ( + item1.name == item2.name + and item1.time.year == item2.time.year + and item1.time.month == item2.time.month + and item1.time.day == item2.time.day + and item1.time.hour == item2.time.hour + and item1.time.minute == item2.time.minute + and item1.time.second == item2.time.second + and item1.time.microsecond == item2.time.microsecond + and item1.version == item2.version + and item1.sample_rate == item2.sample_rate + and item1.sequence == item2.sequence + and item1.instrumentation_key == item2.instrumentation_key + and item1.tags == item2.tags + ) class MockResponse: @@ -989,6 +991,7 @@ def __init__(self, status_code, text, headers={}, reason="test", content="{}"): self.content = content self.raw = MockRaw() + class MockRaw: def __init__(self): self.enforce_content_length = False diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py index 72d68b397109..f04649b17447 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py @@ -11,25 +11,15 @@ class TestConnectionStringParser(unittest.TestCase): def setUp(self): os.environ.clear() - self._valid_connection_string = ( - "InstrumentationKey=1234abcd-5678-4efa-8abc-1234567890ab" - ) - self._valid_instrumentation_key = ( - "1234abcd-5678-4efa-8abc-1234567890ab" - ) + self._valid_connection_string = "InstrumentationKey=1234abcd-5678-4efa-8abc-1234567890ab" + self._valid_instrumentation_key = "1234abcd-5678-4efa-8abc-1234567890ab" def test_validate_connection_String(self): - parser = ConnectionStringParser( - connection_string=self._valid_connection_string - ) - self.assertEqual( - parser._connection_string, self._valid_connection_string - ) + parser = ConnectionStringParser(connection_string=self._valid_connection_string) + self.assertEqual(parser._connection_string, self._valid_connection_string) def test_invalid_key_empty(self): - self.assertRaises( - ValueError, lambda: ConnectionStringParser(connection_string="") - ) + self.assertRaises(ValueError, lambda: ConnectionStringParser(connection_string="")) def test_invalid_key_prefix(self): self.assertRaises( @@ -58,25 +48,19 @@ def test_invalid_key_length(self): def test_invalid_key_dashes(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=1234abcda5678-4efa-8abc-1234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=1234abcda5678-4efa-8abc-1234567890ab"), ) def test_invalid_key_section1_length(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=1234abcda-678-4efa-8abc-1234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=1234abcda-678-4efa-8abc-1234567890ab"), ) def test_invalid_key_section2_length(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=1234abcd-678-a4efa-8abc-1234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=1234abcd-678-a4efa-8abc-1234567890ab"), ) def test_invalid_key_section3_length(self): @@ -91,109 +75,79 @@ def test_invalid_key_section3_length(self): def test_invalid_key_section4_length(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=1234abcd-678-4efa-8bc-11234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=1234abcd-678-4efa-8bc-11234567890ab"), ) def test_invalid_key_section5_length(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=234abcd-678-4efa-8abc-11234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=234abcd-678-4efa-8abc-11234567890ab"), ) def test_invalid_key_section1_hex(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=x234abcd-5678-4efa-8abc-1234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=x234abcd-5678-4efa-8abc-1234567890ab"), ) def test_invalid_key_section2_hex(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=1234abcd-x678-4efa-8abc-1234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=1234abcd-x678-4efa-8abc-1234567890ab"), ) def test_invalid_key_section3_hex(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=1234abcd-5678-4xfa-8abc-1234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=1234abcd-5678-4xfa-8abc-1234567890ab"), ) def test_invalid_key_section4_hex(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=1234abcd-5678-4xfa-8abc-1234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=1234abcd-5678-4xfa-8abc-1234567890ab"), ) def test_invalid_key_section5_hex(self): self.assertRaises( ValueError, - lambda: ConnectionStringParser( - connection_string="InstrumentationKey=1234abcd-5678-4xfa-8abc-1234567890ab" - ), + lambda: ConnectionStringParser(connection_string="InstrumentationKey=1234abcd-5678-4xfa-8abc-1234567890ab"), ) def test_process_options_ikey_code_cs(self): - os.environ[ - "APPLICATIONINSIGHTS_CONNECTION_STRING" - ] = "Authorization=ikey;InstrumentationKey=789" + os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = "Authorization=ikey;InstrumentationKey=789" os.environ["APPINSIGHTS_INSTRUMENTATIONKEY"] = "101112" parser = ConnectionStringParser( - connection_string="Authorization=ikey;InstrumentationKey=" - + self._valid_instrumentation_key, - ) - self.assertEqual( - parser.instrumentation_key, self._valid_instrumentation_key + connection_string="Authorization=ikey;InstrumentationKey=" + self._valid_instrumentation_key, ) + self.assertEqual(parser.instrumentation_key, self._valid_instrumentation_key) def test_process_options_ikey_env_cs(self): os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( - "Authorization=ikey;InstrumentationKey=" - + self._valid_instrumentation_key + "Authorization=ikey;InstrumentationKey=" + self._valid_instrumentation_key ) os.environ["APPINSIGHTS_INSTRUMENTATIONKEY"] = "101112" - parser = ConnectionStringParser( - connection_string=None - ) - self.assertEqual( - parser.instrumentation_key, self._valid_instrumentation_key - ) + parser = ConnectionStringParser(connection_string=None) + self.assertEqual(parser.instrumentation_key, self._valid_instrumentation_key) def test_process_options_ikey_env_ikey(self): - os.environ[ - "APPINSIGHTS_INSTRUMENTATIONKEY" - ] = self._valid_instrumentation_key - parser = ConnectionStringParser( - connection_string=None - ) - self.assertEqual( - parser.instrumentation_key, self._valid_instrumentation_key - ) + os.environ["APPINSIGHTS_INSTRUMENTATIONKEY"] = self._valid_instrumentation_key + parser = ConnectionStringParser(connection_string=None) + self.assertEqual(parser.instrumentation_key, self._valid_instrumentation_key) def test_process_options_endpoint_code_cs(self): - os.environ[ - "APPLICATIONINSIGHTS_CONNECTION_STRING" - ] = "Authorization=ikey;IngestionEndpoint=456;InstrumentationKey=" + self._valid_instrumentation_key + os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( + "Authorization=ikey;IngestionEndpoint=456;InstrumentationKey=" + self._valid_instrumentation_key + ) parser = ConnectionStringParser( connection_string="Authorization=ikey;IngestionEndpoint=123", ) self.assertEqual(parser.endpoint, "123") def test_process_options_endpoint_env_cs(self): - os.environ[ - "APPLICATIONINSIGHTS_CONNECTION_STRING" - ] = "Authorization=ikey;IngestionEndpoint=456;InstrumentationKey=" + self._valid_instrumentation_key + os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( + "Authorization=ikey;IngestionEndpoint=456;InstrumentationKey=" + self._valid_instrumentation_key + ) parser = ConnectionStringParser( connection_string=None, ) @@ -203,14 +157,12 @@ def test_process_options_endpoint_default(self): parser = ConnectionStringParser( connection_string=self._valid_connection_string, ) - self.assertEqual( - parser.endpoint, "https://dc.services.visualstudio.com" - ) + self.assertEqual(parser.endpoint, "https://dc.services.visualstudio.com") def test_process_options_live_endpoint_code_cs(self): - os.environ[ - "APPLICATIONINSIGHTS_CONNECTION_STRING" - ] = "Authorization=ikey;IngestionEndpoint=456;InstrumentationKey=" + self._valid_instrumentation_key + os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( + "Authorization=ikey;IngestionEndpoint=456;InstrumentationKey=" + self._valid_instrumentation_key + ) parser = ConnectionStringParser( connection_string="Authorization=ikey;IngestionEndpoint=123;LiveEndpoint=111", ) @@ -218,9 +170,10 @@ def test_process_options_live_endpoint_code_cs(self): self.assertEqual(parser.live_endpoint, "111") def test_process_options_live_endpoint_env_cs(self): - os.environ[ - "APPLICATIONINSIGHTS_CONNECTION_STRING" - ] = "Authorization=ikey;IngestionEndpoint=456;LiveEndpoint=111;InstrumentationKey=" + self._valid_instrumentation_key + os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( + "Authorization=ikey;IngestionEndpoint=456;LiveEndpoint=111;InstrumentationKey=" + + self._valid_instrumentation_key + ) parser = ConnectionStringParser( connection_string=None, ) @@ -231,14 +184,10 @@ def test_process_options_live_endpoint_default(self): parser = ConnectionStringParser( connection_string=self._valid_connection_string, ) - self.assertEqual( - parser.live_endpoint, "https://rt.services.visualstudio.com" - ) + self.assertEqual(parser.live_endpoint, "https://rt.services.visualstudio.com") def test_parse_connection_string_invalid(self): - self.assertRaises( - ValueError, lambda: ConnectionStringParser(connection_string="asd") - ) + self.assertRaises(ValueError, lambda: ConnectionStringParser(connection_string="asd")) def test_parse_connection_string_invalid_auth(self): self.assertRaises( @@ -250,14 +199,14 @@ def test_parse_connection_string_invalid_auth(self): def test_parse_connection_string_suffix(self): parser = ConnectionStringParser( - connection_string="Authorization=ikey;EndpointSuffix=123;Location=US;InstrumentationKey=" + - self._valid_instrumentation_key, + connection_string="Authorization=ikey;EndpointSuffix=123;Location=US;InstrumentationKey=" + + self._valid_instrumentation_key, ) self.assertEqual(parser.endpoint, "https://US.dc.123") def test_parse_connection_string_suffix_no_location(self): parser = ConnectionStringParser( - connection_string="Authorization=ikey;EndpointSuffix=123;InstrumentationKey=" + - self._valid_instrumentation_key, + connection_string="Authorization=ikey;EndpointSuffix=123;InstrumentationKey=" + + self._valid_instrumentation_key, ) self.assertEqual(parser.endpoint, "https://dc.123") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py index 050abdc0c567..7c7518d47f8e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py @@ -15,6 +15,7 @@ TEST_FOLDER = os.path.abspath(".test.storage") + def throw(exc_type, *args, **kwargs): def func(*_args, **_kwargs): raise exc_type(*args, **kwargs) @@ -32,7 +33,7 @@ def clean_folder(folder): elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: - print('Failed to delete %s. Reason: %s' % (file_path, e)) + print("Failed to delete %s. Reason: %s" % (file_path, e)) # pylint: disable=no-self-use diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py index 668cca69cec0..bb8c2c077553 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py @@ -30,48 +30,44 @@ TEST_TIME = "TEST_TIME" TEST_WEBSITE_SITE_NAME = "TEST_WEBSITE_SITE_NAME" + class TestUtils(unittest.TestCase): def setUp(self): os.environ.clear() - self._valid_instrumentation_key = ( - "1234abcd-5678-4efa-8abc-1234567890ab" - ) + self._valid_instrumentation_key = "1234abcd-5678-4efa-8abc-1234567890ab" def test_nanoseconds_to_duration(self): ns_to_duration = _utils.ns_to_duration self.assertEqual(ns_to_duration(0), "0.00:00:00.000") - self.assertEqual(ns_to_duration(500000), "0.00:00:00.001") # Rounding + self.assertEqual(ns_to_duration(500000), "0.00:00:00.001") # Rounding self.assertEqual(ns_to_duration(1000000), "0.00:00:00.001") - self.assertEqual(ns_to_duration(1500000), "0.00:00:00.002") # Rounding + self.assertEqual(ns_to_duration(1500000), "0.00:00:00.002") # Rounding self.assertEqual(ns_to_duration(1000000000), "0.00:00:01.000") self.assertEqual(ns_to_duration(60 * 1000000000), "0.00:01:00.000") self.assertEqual(ns_to_duration(3600 * 1000000000), "0.01:00:00.000") self.assertEqual(ns_to_duration(86400 * 1000000000), "1.00:00:00.000") - @patch("time.time") def test_ticks_since_dot_net_epoch(self, time_mock): current_time = time.time() shift_time = int( - ( - datetime.datetime(1970, 1, 1, 0, 0, 0) - - datetime.datetime(1, 1, 1, 0, 0, 0)).total_seconds() - ) * (10 ** 7) + (datetime.datetime(1970, 1, 1, 0, 0, 0) - datetime.datetime(1, 1, 1, 0, 0, 0)).total_seconds() + ) * (10**7) time_mock.return_value = current_time ticks = _utils._ticks_since_dot_net_epoch() expected_ticks = int(current_time * (10**7)) + shift_time self.assertEqual(ticks, expected_ticks) - def test_populate_part_a_fields(self): resource = Resource( - {"service.name": "testServiceName", - "service.namespace": "testServiceNamespace", - "service.instance.id": "testServiceInstanceId", - "device.id": "testDeviceId", - "device.model.name": "testDeviceModel", - "device.manufacturer": "testDeviceMake", - "service.version": "testApplicationVer", + { + "service.name": "testServiceName", + "service.namespace": "testServiceNamespace", + "service.instance.id": "testServiceInstanceId", + "device.id": "testDeviceId", + "device.model.name": "testDeviceModel", + "device.manufacturer": "testDeviceMake", + "service.version": "testApplicationVer", } ) tags = _utils._populate_part_a_fields(resource) @@ -85,8 +81,7 @@ def test_populate_part_a_fields(self): self.assertEqual(tags.get("ai.application.ver"), "testApplicationVer") def test_populate_part_a_fields_default(self): - resource = Resource( - {"service.name": "testServiceName"}) + resource = Resource({"service.name": "testServiceName"}) tags = _utils._populate_part_a_fields(resource) self.assertIsNotNone(tags) self.assertEqual(tags.get("ai.cloud.role"), "testServiceName") @@ -146,42 +141,54 @@ def test_get_sdk_version_prefix_attach_windows(self, mock_system, mock_getenv): # App Service SDK Version Prefix - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True + ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=False) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") def test_get_sdk_version_prefix_app_service(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "aum_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True + ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=False) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux") def test_get_sdk_version_prefix_app_service_linux(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "alm_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True + ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=False) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows") def test_get_sdk_version_prefix_app_service_windows(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "awm_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True + ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=True) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") def test_get_sdk_version_prefix_app_service_attach(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "aui_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True + ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=True) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux") def test_get_sdk_version_prefix_app_service_linux_attach(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "ali_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, clear=True + ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=True) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows") def test_get_sdk_version_prefix_app_service_windows_attach(self, mock_system, mock_getenv): @@ -190,42 +197,66 @@ def test_get_sdk_version_prefix_app_service_windows_attach(self, mock_system, mo # Function SDK Version Prefix - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", + {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, + clear=True, + ) @patch("azure.monitor.opentelemetry.exporter._utils._is_attach_enabled", return_value=False) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") def test_get_sdk_version_prefix_function(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fum_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", + {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, + clear=True, + ) @patch("azure.monitor.opentelemetry.exporter._utils._is_attach_enabled", return_value=False) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux") def test_get_sdk_version_prefix_function_linux(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "flm_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", + {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, + clear=True, + ) @patch("azure.monitor.opentelemetry.exporter._utils._is_attach_enabled", return_value=False) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows") def test_get_sdk_version_prefix_function_windows(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fwm_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", + {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, + clear=True, + ) @patch("azure.monitor.opentelemetry.exporter._utils._is_attach_enabled", return_value=True) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") def test_get_sdk_version_prefix_function_attach(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fui_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", + {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, + clear=True, + ) @patch("azure.monitor.opentelemetry.exporter._utils._is_attach_enabled", return_value=True) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux") def test_get_sdk_version_prefix_function_linux_attach(self, mock_system, mock_getenv): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fli_") - @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, clear=True) + @patch.dict( + "azure.monitor.opentelemetry.exporter._utils.environ", + {"FUNCTIONS_WORKER_RUNTIME": TEST_WEBSITE_SITE_NAME}, + clear=True, + ) @patch("azure.monitor.opentelemetry.exporter._utils._is_attach_enabled", return_value=True) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows") def test_get_sdk_version_prefix_function_windows_attach(self, mock_system, mock_getenv): @@ -240,9 +271,7 @@ def test_get_sdk_version_prefix_function_windows_attach(self, mock_system, mock_ ) @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}) def test_attach_enabled(self, mock_isdir): - self.assertEqual( - _utils._is_attach_enabled(), True - ) + self.assertEqual(_utils._is_attach_enabled(), True) @patch( "azure.monitor.opentelemetry.exporter._utils.isdir", @@ -250,9 +279,7 @@ def test_attach_enabled(self, mock_isdir): ) @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}) def test_attach_app_service_disabled(self, mock_isdir): - self.assertEqual( - _utils._is_attach_enabled(), False - ) + self.assertEqual(_utils._is_attach_enabled(), False) @patch( "azure.monitor.opentelemetry.exporter._utils.isdir", @@ -261,6 +288,4 @@ def test_attach_app_service_disabled(self, mock_isdir): @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {}, clear=True) def test_attach_off_app_service_with_agent(self, mock_isdir): # This is not an expected scenario and just tests the default - self.assertEqual( - _utils._is_attach_enabled(), False - ) + self.assertEqual(_utils._is_attach_enabled(), False) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_sampling.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_sampling.py index d443c38f381c..0499a4e2f4e1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_sampling.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_sampling.py @@ -8,6 +8,7 @@ azure_monitor_opentelemetry_sampler_factory, ) + # pylint: disable=protected-access class TestApplicationInsightsSampler(unittest.TestCase): @@ -22,14 +23,10 @@ def test_constructor_ratio(self): self.assertEqual(sampler._sample_rate, 75) def test_invalid_ratio(self): - self.assertRaises( - ValueError, lambda: ApplicationInsightsSampler(1.01) - ) - self.assertRaises( - ValueError, lambda: ApplicationInsightsSampler(-0.01) - ) - - @mock.patch.object(ApplicationInsightsSampler, '_get_DJB2_sample_score') + self.assertRaises(ValueError, lambda: ApplicationInsightsSampler(1.01)) + self.assertRaises(ValueError, lambda: ApplicationInsightsSampler(-0.01)) + + @mock.patch.object(ApplicationInsightsSampler, "_get_DJB2_sample_score") def test_should_sample(self, score_mock): sampler = ApplicationInsightsSampler(0.75) score_mock.return_value = 0.7 @@ -37,7 +34,7 @@ def test_should_sample(self, score_mock): self.assertEqual(result.attributes["_MS.sampleRate"], 75) self.assertTrue(result.decision.is_sampled()) - @mock.patch.object(ApplicationInsightsSampler, '_get_DJB2_sample_score') + @mock.patch.object(ApplicationInsightsSampler, "_get_DJB2_sample_score") def test_should_sample_not_sampled(self, score_mock): sampler = ApplicationInsightsSampler(0.5) score_mock.return_value = 0.7 diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py index 3d76c77e74c2..52c46b0b88ea 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py @@ -50,9 +50,7 @@ class TestAzureTraceExporter(unittest.TestCase): @classmethod def setUpClass(cls): os.environ.clear() - os.environ[ - "APPINSIGHTS_INSTRUMENTATIONKEY" - ] = "1234abcd-5678-4efa-8abc-1234567890ab" + os.environ["APPINSIGHTS_INSTRUMENTATIONKEY"] = "1234abcd-5678-4efa-8abc-1234567890ab" os.environ["APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL"] = "true" os.environ["APPLICATIONINSIGHTS_OPENTELEMETRY_RESOURCE_METRIC_DISABLED"] = "true" cls._exporter = AzureMonitorTraceExporter( @@ -259,33 +257,47 @@ def test_export_not_retryable(self): def test_span_to_envelope_partA(self): exporter = self._exporter resource = resources.Resource( - {"service.name": "testServiceName", - "service.namespace": "testServiceNamespace", - "service.instance.id": "testServiceInstanceId"}) + { + "service.name": "testServiceName", + "service.namespace": "testServiceNamespace", + "service.instance.id": "testServiceInstanceId", + } + ) context = SpanContext( - trace_id=36873507687745823477771305566750195431, - span_id=12030755672171557338, - is_remote=False, - ) + trace_id=36873507687745823477771305566750195431, + span_id=12030755672171557338, + is_remote=False, + ) test_span = trace._Span( name="test", context=context, resource=resource, - attributes={"enduser.id":"testId"}, + attributes={"enduser.id": "testId"}, parent=context, ) test_span.start() test_span.end() envelope = exporter._span_to_envelope(test_span) - self.assertEqual(envelope.instrumentation_key, - "1234abcd-5678-4efa-8abc-1234567890ab") + self.assertEqual(envelope.instrumentation_key, "1234abcd-5678-4efa-8abc-1234567890ab") self.assertIsNotNone(envelope.tags) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION]) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), + azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION], + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), + azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION], + ) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE), "testServiceNamespace.testServiceName") self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), "testServiceInstanceId") @@ -296,13 +308,12 @@ def test_span_to_envelope_partA(self): def test_span_to_envelope_partA_default(self): exporter = self._exporter - resource = resources.Resource( - {"service.name": "testServiceName"}) + resource = resources.Resource({"service.name": "testServiceName"}) context = SpanContext( - trace_id=36873507687745823477771305566750195431, - span_id=12030755672171557338, - is_remote=False, - ) + trace_id=36873507687745823477771305566750195431, + span_id=12030755672171557338, + is_remote=False, + ) test_span = trace._Span( name="test", context=context, @@ -313,7 +324,10 @@ def test_span_to_envelope_partA_default(self): envelope = exporter._span_to_envelope(test_span) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE), "testServiceName") self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), platform.node()) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_NODE_NAME), envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE)) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_NODE_NAME), + envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), + ) def test_span_to_envelope_client_http(self): exporter = self._exporter @@ -341,10 +355,8 @@ def test_span_to_envelope_client_http(self): span.end(end_time=end_time) span._status = Status(status_code=StatusCode.OK) envelope = exporter._span_to_envelope(span) - - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.RemoteDependency" - ) + + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.RemoteDependency") self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(envelope.data.base_data.name, "GET /wiki/Rabbit") self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") @@ -412,7 +424,7 @@ def test_span_to_envelope_client_http(self): "http.method": "GET", "http.scheme": "https", "http.host": "www.wikipedia.org", - "http.target": "/path/12314/?q=ddds#123" + "http.target": "/path/12314/?q=ddds#123", } envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.data.base_data.data, "https://www.wikipedia.org/path/12314/?q=ddds#123") @@ -422,7 +434,7 @@ def test_span_to_envelope_client_http(self): "http.scheme": "https", "net.peer.port": "8080", "net.peer.name": "example.com", - "http.target": "/path/12314/?q=ddds#123" + "http.target": "/path/12314/?q=ddds#123", } envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.data.base_data.data, "https://example.com:8080/path/12314/?q=ddds#123") @@ -432,7 +444,7 @@ def test_span_to_envelope_client_http(self): "http.scheme": "https", "net.peer.port": "8080", "net.peer.ip": "192.168.0.1", - "http.target": "/path/12314/?q=ddds#123" + "http.target": "/path/12314/?q=ddds#123", } envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.data.base_data.data, "https://192.168.0.1:8080/path/12314/?q=ddds#123") @@ -442,7 +454,7 @@ def test_span_to_envelope_client_http(self): "http.method": "GET", "http.scheme": "https", "http.url": "https://www.example.com", - "http.status_code": None + "http.status_code": None, } envelope = exporter._span_to_envelope(span) envelope = exporter._span_to_envelope(span) @@ -489,10 +501,8 @@ def test_span_to_envelope_client_db(self): span.end(end_time=end_time) span._status = Status(status_code=StatusCode.OK) envelope = exporter._span_to_envelope(span) - - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.RemoteDependency" - ) + + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.RemoteDependency") self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(envelope.data.base_data.name, "test") self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") @@ -609,10 +619,8 @@ def test_span_to_envelope_client_rpc(self): span.end(end_time=end_time) span._status = Status(status_code=StatusCode.OK) envelope = exporter._span_to_envelope(span) - - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.RemoteDependency" - ) + + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.RemoteDependency") self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(envelope.data.base_data.name, "test") self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") @@ -624,7 +632,7 @@ def test_span_to_envelope_client_rpc(self): self.assertEqual(envelope.data.base_data.type, "rpc.system") self.assertEqual(envelope.data.base_data.target, "service") self.assertEqual(len(envelope.data.base_data.properties), 0) - + # target span._attributes = { "rpc.system": "rpc", @@ -656,10 +664,8 @@ def test_span_to_envelope_client_messaging(self): span.end(end_time=end_time) span._status = Status(status_code=StatusCode.OK) envelope = exporter._span_to_envelope(span) - - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.RemoteDependency" - ) + + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.RemoteDependency") self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(envelope.data.base_data.name, "test") self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") @@ -671,7 +677,7 @@ def test_span_to_envelope_client_messaging(self): self.assertEqual(envelope.data.base_data.type, "messaging") self.assertEqual(envelope.data.base_data.target, "celery") self.assertEqual(len(envelope.data.base_data.properties), 0) - + # target span._attributes = { "messaging.system": "messaging", @@ -679,6 +685,41 @@ def test_span_to_envelope_client_messaging(self): envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.data.base_data.target, "messaging") + def test_span_to_envelope_client_gen_ai(self): + exporter = self._exporter + start_time = 1575494316027613500 + end_time = start_time + 1001000000 + + # SpanKind.CLIENT messaging + span = trace._Span( + name="test", + context=SpanContext( + trace_id=36873507687745823477771305566750195431, + span_id=12030755672171557337, + is_remote=False, + ), + attributes={ + "gen_ai.system": "az.ai.inference", + }, + kind=SpanKind.CLIENT, + ) + span.start(start_time=start_time) + span.end(end_time=end_time) + span._status = Status(status_code=StatusCode.UNSET) + envelope = exporter._span_to_envelope(span) + + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.RemoteDependency") + self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") + self.assertEqual(envelope.data.base_data.name, "test") + self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") + self.assertEqual(envelope.data.base_data.duration, "0.00:00:01.001") + self.assertTrue(envelope.data.base_data.success) + self.assertEqual(envelope.data.base_data.result_code, "0") + + self.assertEqual(envelope.data.base_type, "RemoteDependencyData") + self.assertEqual(envelope.data.base_data.type, "az.ai.inference") + self.assertEqual(len(envelope.data.base_data.properties), 1) + def test_span_to_envelope_client_azure(self): exporter = self._exporter start_time = 1575494316027613500 @@ -703,10 +744,8 @@ def test_span_to_envelope_client_azure(self): span.end(end_time=end_time) span._status = Status(status_code=StatusCode.OK) envelope = exporter._span_to_envelope(span) - - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.RemoteDependency" - ) + + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.RemoteDependency") self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(envelope.data.base_data.name, "test") self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") @@ -718,7 +757,7 @@ def test_span_to_envelope_client_azure(self): self.assertEqual(envelope.data.base_data.type, "Microsoft.EventHub") self.assertEqual(envelope.data.base_data.target, "test_address/test_destination") self.assertEqual(len(envelope.data.base_data.properties), 2) - + # target span._attributes = { "messaging.system": "messaging", @@ -749,10 +788,8 @@ def test_span_to_envelope_producer_messaging(self): span.end(end_time=end_time) span._status = Status(status_code=StatusCode.OK) envelope = exporter._span_to_envelope(span) - - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.RemoteDependency" - ) + + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.RemoteDependency") self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(envelope.data.base_data.name, "test") self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") @@ -791,10 +828,10 @@ def test_span_to_envelope_internal(self): # SpanKind.INTERNAL context = SpanContext( - trace_id=36873507687745823477771305566750195431, - span_id=12030755672171557337, - is_remote=False, - ) + trace_id=36873507687745823477771305566750195431, + span_id=12030755672171557337, + is_remote=False, + ) span = trace._Span( name="test", context=context, @@ -806,10 +843,8 @@ def test_span_to_envelope_internal(self): span.end(end_time=end_time) span._status = Status(status_code=StatusCode.OK) envelope = exporter._span_to_envelope(span) - - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.RemoteDependency" - ) + + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.RemoteDependency") self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(envelope.data.base_data.name, "test") self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") @@ -843,9 +878,7 @@ def test_span_envelope_request_azure(self): span_id=12030755672171557338, is_remote=False, ), - attributes={ - "enqueuedTime": 1000000000000 - } + attributes={"enqueuedTime": 1000000000000}, ) ) links.append( @@ -855,9 +888,7 @@ def test_span_envelope_request_azure(self): span_id=12030755672171557338, is_remote=False, ), - attributes={ - "enqueuedTime": 3000000000000 - } + attributes={"enqueuedTime": 3000000000000}, ) ) span = trace._Span( @@ -879,9 +910,7 @@ def test_span_envelope_request_azure(self): span.start(start_time=start_time) span.end(end_time=end_time) envelope = exporter._span_to_envelope(span) - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.Request" - ) + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Request") self.assertEqual(envelope.tags[ContextTagKeys.AI_OPERATION_NAME], "test") self.assertEqual(envelope.data.base_type, "RequestData") self.assertEqual(envelope.data.base_data.name, "test") @@ -902,9 +931,7 @@ def test_span_envelope_request_azure(self): span_id=12030755672171557338, is_remote=False, ), - attributes={ - "enqueuedTime": 5000000000000 - } + attributes={"enqueuedTime": 5000000000000}, ) ) links.append( @@ -914,16 +941,13 @@ def test_span_envelope_request_azure(self): span_id=12030755672171557338, is_remote=False, ), - attributes={ - "enqueuedTime": 6000000000000 - } + attributes={"enqueuedTime": 6000000000000}, ) ) span._links = links envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.data.base_data.measurements["timeSinceEnqueued"], 0) - def test_span_envelope_server_http(self): exporter = self._exporter start_time = 1575494316027613500 @@ -952,9 +976,7 @@ def test_span_envelope_server_http(self): span.start(start_time=start_time) span.end(end_time=end_time) envelope = exporter._span_to_envelope(span) - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.Request" - ) + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Request") self.assertEqual(envelope.data.base_type, "RequestData") self.assertEqual(envelope.data.base_data.name, "GET /wiki/Rabbit") self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") @@ -967,7 +989,7 @@ def test_span_envelope_server_http(self): self.assertEqual(envelope.tags[ContextTagKeys.AI_LOCATION_IP], "client_ip") self.assertEqual(envelope.data.base_data.url, "https://www.wikipedia.org/wiki/Rabbit") self.assertEqual(len(envelope.data.base_data.properties), 0) - + # success span._attributes = { "http.method": "GET", @@ -996,10 +1018,7 @@ def test_span_envelope_server_http(self): self.assertEqual(envelope.data.base_data.response_code, "0") # location - span._attributes = { - "http.method": "GET", - "net.peer.ip": "peer_ip" - } + span._attributes = {"http.method": "GET", "net.peer.ip": "peer_ip"} envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.tags[ContextTagKeys.AI_LOCATION_IP], "peer_ip") @@ -1080,7 +1099,7 @@ def test_span_envelope_server_messaging(self): self.assertEqual(envelope.data.base_data.id, "a6f5d48acb4d31d9") self.assertEqual(envelope.data.base_data.duration, "0.00:00:01.001") self.assertTrue(envelope.data.base_data.success) - + self.assertEqual(envelope.tags[ContextTagKeys.AI_LOCATION_IP], "127.0.0.1") self.assertEqual(envelope.data.base_data.source, "test name/celery") self.assertEqual(len(envelope.data.base_data.properties), 0) @@ -1220,9 +1239,7 @@ def test_span_to_envelope_properties_links(self): span.end(end_time=end_time) envelope = exporter._span_to_envelope(span) self.assertEqual(len(envelope.data.base_data.properties), 1) - json_dict = json.loads( - envelope.data.base_data.properties["_MS.links"] - )[0] + json_dict = json.loads(envelope.data.base_data.properties["_MS.links"])[0] self.assertEqual(json_dict["id"], "a6f5d48acb4d31da") def test_span_to_envelope_properties_std_metrics(self): @@ -1243,7 +1260,7 @@ def test_span_to_envelope_properties_std_metrics(self): "http.status_code": 200, }, kind=SpanKind.CLIENT, - instrumentation_scope=InstrumentationScope("opentelemetry.instrumentation.requests") + instrumentation_scope=InstrumentationScope("opentelemetry.instrumentation.requests"), ) span._status = Status(status_code=StatusCode.OK) span.start(start_time=start_time) @@ -1281,22 +1298,33 @@ def test_span_events_to_envelopes_exception(self): span.end() span._status = Status(status_code=StatusCode.OK) envelopes = exporter._span_events_to_envelopes(span) - + self.assertEqual(len(envelopes), 1) envelope = envelopes[0] + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Exception") + self.assertEqual(envelope.instrumentation_key, "1234abcd-5678-4efa-8abc-1234567890ab") + self.assertIsNotNone(envelope.tags) self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.Exception" + envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), + azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION], + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), + azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION], ) - self.assertEqual(envelope.instrumentation_key, - "1234abcd-5678-4efa-8abc-1234567890ab") - self.assertIsNotNone(envelope.tags) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION]) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_ID), "{:032x}".format(span.context.trace_id)) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_PARENT_ID), "{:016x}".format(span.context.span_id)) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_OPERATION_PARENT_ID), "{:016x}".format(span.context.span_id) + ) self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(len(envelope.data.base_data.properties), 0) self.assertEqual(len(envelope.data.base_data.exceptions), 1) @@ -1332,22 +1360,33 @@ def test_span_events_to_envelopes_message(self): span.end() span._status = Status(status_code=StatusCode.OK) envelopes = exporter._span_events_to_envelopes(span) - + self.assertEqual(len(envelopes), 1) envelope = envelopes[0] + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") + self.assertEqual(envelope.instrumentation_key, "1234abcd-5678-4efa-8abc-1234567890ab") + self.assertIsNotNone(envelope.tags) self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.Message" + envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), + azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION], + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), + azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION], ) - self.assertEqual(envelope.instrumentation_key, - "1234abcd-5678-4efa-8abc-1234567890ab") - self.assertIsNotNone(envelope.tags) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION]) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_ID), "{:032x}".format(span.context.trace_id)) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_PARENT_ID), "{:016x}".format(span.context.span_id)) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_OPERATION_PARENT_ID), "{:016x}".format(span.context.span_id) + ) self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(len(envelope.data.base_data.properties), 1) self.assertEqual(envelope.data.base_data.properties["test"], "asd") @@ -1373,7 +1412,7 @@ def test_span_events_to_envelopes_sample_rate(self): kind=SpanKind.CLIENT, attributes={ "_MS.sampleRate": 50, - } + }, ) attributes = { "test": "asd", @@ -1384,23 +1423,34 @@ def test_span_events_to_envelopes_sample_rate(self): span.end() span._status = Status(status_code=StatusCode.OK) envelopes = exporter._span_events_to_envelopes(span) - + self.assertEqual(len(envelopes), 1) envelope = envelopes[0] - self.assertEqual( - envelope.name, "Microsoft.ApplicationInsights.Message" - ) + self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") self.assertEqual(envelope.sample_rate, 50) - self.assertEqual(envelope.instrumentation_key, - "1234abcd-5678-4efa-8abc-1234567890ab") + self.assertEqual(envelope.instrumentation_key, "1234abcd-5678-4efa-8abc-1234567890ab") self.assertIsNotNone(envelope.tags) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE]) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION]) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_ID), azure_monitor_context[ContextTagKeys.AI_DEVICE_ID] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_LOCALE), azure_monitor_context[ContextTagKeys.AI_DEVICE_LOCALE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_OS_VERSION), + azure_monitor_context[ContextTagKeys.AI_DEVICE_OS_VERSION], + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_DEVICE_TYPE), azure_monitor_context[ContextTagKeys.AI_DEVICE_TYPE] + ) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_INTERNAL_SDK_VERSION), + azure_monitor_context[ContextTagKeys.AI_INTERNAL_SDK_VERSION], + ) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_ID), "{:032x}".format(span.context.trace_id)) - self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_PARENT_ID), "{:016x}".format(span.context.span_id)) + self.assertEqual( + envelope.tags.get(ContextTagKeys.AI_OPERATION_PARENT_ID), "{:016x}".format(span.context.span_id) + ) self.assertEqual(envelope.time, "2019-12-04T21:18:36.027613Z") self.assertEqual(len(envelope.data.base_data.properties), 1) self.assertEqual(envelope.data.base_data.properties["test"], "asd") @@ -1446,10 +1496,7 @@ def test_export_otel_resource_metric(self, mock_get_tracer_provider): result = exporter.export([test_span]) self.assertEqual(result, SpanExportResult.SUCCESS) mock_get_otel_resource_envelope.assert_called_once_with(test_resource) - envelopes = [ - "test_envelope", - exporter._span_to_envelope(test_span) - ] + envelopes = ["test_envelope", exporter._span_to_envelope(test_span)] transmit.assert_called_once_with(envelopes) def test_get_otel_resource_envelope(self): @@ -1468,7 +1515,7 @@ def test_get_otel_resource_envelope(self): self.assertEqual(metric_name, "Microsoft.ApplicationInsights.Metric") instrumentation_key = envelope.instrumentation_key self.assertEqual(instrumentation_key, exporter._instrumentation_key) - + monitor_base = envelope.data self.assertEqual(monitor_base.base_type, "MetricData") metrics_data = monitor_base.base_data @@ -1502,9 +1549,7 @@ def test_check_instrumentation_span(self): span = mock.Mock() span.attributes = {} span.instrumentation_scope.name = "opentelemetry.instrumentation.test" - with mock.patch( - "azure.monitor.opentelemetry.exporter._utils.add_instrumentation" - ) as add: + with mock.patch("azure.monitor.opentelemetry.exporter._utils.add_instrumentation") as add: _check_instrumentation_span(span) add.assert_called_once_with("test") @@ -1512,9 +1557,7 @@ def test_check_instrumentation_span_not_instrumentation(self): span = mock.Mock() span.attributes = {} span.instrumentation_scope.name = "__main__" - with mock.patch( - "azure.monitor.opentelemetry.exporter._utils.add_instrumentation" - ) as add: + with mock.patch("azure.monitor.opentelemetry.exporter._utils.add_instrumentation") as add: _check_instrumentation_span(span) add.assert_not_called() @@ -1522,8 +1565,6 @@ def test_check_instrumentation_span_azure_sdk(self): span = mock.Mock() span.attributes = {_AZURE_SDK_NAMESPACE_NAME: "Microsoft.EventHub"} span.instrumentation_scope.name = "__main__" - with mock.patch( - "azure.monitor.opentelemetry.exporter._utils.add_instrumentation" - ) as add: + with mock.patch("azure.monitor.opentelemetry.exporter._utils.add_instrumentation") as add: _check_instrumentation_span(span) add.assert_called_once_with(_AZURE_SDK_OPENTELEMETRY_NAME)