diff --git a/CHANGELOG.md b/CHANGELOG.md index be507ccc..440f2f4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,13 @@ ## Unreleased -## [1.0.0b11](https://github.com/microsoft/ApplicationInsights-Python/releases/tag/v1.0.0b11) - 2023-04-12 - +- Remove most configuration for Public Preview + ([#277](https://github.com/microsoft/ApplicationInsights-Python/pull/277)) - Infer telemetry category disablement from exporter environment variables ([#278](https://github.com/microsoft/ApplicationInsights-Python/pull/278)) + +## [1.0.0b11](https://github.com/microsoft/ApplicationInsights-Python/releases/tag/v1.0.0b11) - 2023-04-12 + - Reverse default behavior of instrumentations and implement configuration for exclusion ([#253](https://github.com/microsoft/ApplicationInsights-Python/pull/253)) - Use entrypoints instead of importlib to load instrumentations diff --git a/azure-monitor-opentelemetry/README.md b/azure-monitor-opentelemetry/README.md index e8e2c87f..d82a850e 100644 --- a/azure-monitor-opentelemetry/README.md +++ b/azure-monitor-opentelemetry/README.md @@ -55,38 +55,20 @@ You can use `configure_azure_monitor` to set up instrumentation for your app to | Parameter | Description | Environment Variable | |-------------------|----------------------------------------------------|----------------------| | `connection_string` | The [connection string][connection_string_doc] for your Application Insights resource. The connection string will be automatically populated from the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable if not explicitly passed in. | `APPLICATIONINSIGHTS_CONNECTION_STRING` | -| `exclude_instrumentations` | By default, all supported [instrumentations](#officially-supported-instrumentations) are enabled to collect telemetry. Specify instrumentations you do not want to enable to collect telemetry by passing in a comma separated list of instrumented library names. e.g. `["requests", "flask"]` | | -| `resource` | Specifies the OpenTelemetry [resource][opentelemetry_spec_resource] associated with your application. See [this][ot_sdk_python_resource] for default behavior. | [OTEL_SERVICE_NAME][opentelemetry_spec_service_name], [OTEL_RESOURCE_ATTRIBUTES][opentelemetry_spec_resource_attributes] | -| `disable_logging` | If set to `True`, disables collection and export of logging telemetry. Defaults to `False`. | | -| `disable_metrics` | If set to `True`, disables collection and export of metric telemetry. Defaults to `False`. | | -| `disable_tracing` | If set to `True`, disables collection and export of distributed tracing telemetry. Defaults to `False`. | | -| `logging_level` | Specifies the [logging level][logging_level] of the logs you would like to collect for your logging pipeline. Defaults to 0 which is `logging.NOTSET`. | | -| `logger_name` | Specifies the [logger name][logger_name_hierarchy_doc] under which logging will be instrumented. Defaults to "" which corresponds to the root logger. | | -| `logging_export_interval_ms`| Specifies the logging export interval in milliseconds. Defaults to 5000. | `OTEL_BLRP_SCHEDULE_DELAY` | -| `metric_readers` | Specifies the [metric readers][ot_metric_reader] that you would like to use for your metric pipeline. Accepts a list of [metric readers][ot_sdk_python_metric_reader]. | | -| `views` | Specifies the list of [views][opentelemetry_spec_view] to configure for the metric pipeline. See [here][ot_sdk_python_view_examples] for example usage. | | -| `sampling_ratio` | Specifies the ratio of distributed tracing telemetry to be [sampled][application_insights_sampling]. Accepted values are in the range [0,1]. Defaults to 1.0, meaning no telemetry is sampled out. | `OTEL_TRACES_SAMPLER_ARG` | -| `tracing_export_interval_ms`| Specifies the distributed tracing export interval in milliseconds. Defaults to 5000. | `OTEL_BSP_SCHEDULE_DELAY` | -| `instrumentation_config` | Specifies a dictionary of kwargs that will be applied to instrumentation configuration. You can specify which instrumentation you want to configure by name in the key field and value as a dictionary representing `kwargs` for the corresponding instrumentation. Refer to the `Supported Library` section [above](#officially-supported-instrumentations) for the list of supported library names. | | - -Example for use of `instrumentation_config`: -```python -... -configure_azure_monitor( - connection_string="", - instrumentation_config={ - "flask": { - "excluded_urls": "http://localhost:8080/ignore", - }, - "requests": { - "excluded_urls": "http://example.com" - } - } -) -... -``` -Take a look at the specific [instrumenation][ot_instrumentations] documentation for available configurations. + +You can configure further with [OpenTelemetry environment variables][ot_env_vars] such as: +| Environment Variable | Description | +|-------------|----------------------| +| [OTEL_SERVICE_NAME][opentelemetry_spec_service_name], [OTEL_RESOURCE_ATTRIBUTES][opentelemetry_spec_resource_attributes] | Specifies the OpenTelemetry [resource][opentelemetry_spec_resource] associated with your application. | +| `OTEL_LOGS_EXPORTER` | If set to `None`, disables collection and export of logging telemetry. | +| `OTEL_METRICS_EXPORTER` | If set to `None`, disables collection and export of metric telemetry. | +| `OTEL_TRACES_EXPORTER` | If set to `None`, disables collection and export of distributed tracing telemetry. | +| `OTEL_BLRP_SCHEDULE_DELAY` | Specifies the logging export interval in milliseconds. Defaults to 5000. | +| `OTEL_BSP_SCHEDULE_DELAY` | Specifies the distributed tracing export interval in milliseconds. Defaults to 5000. | +| `OTEL_TRACES_SAMPLER_ARG` | Specifies the ratio of distributed tracing telemetry to be [sampled][application_insights_sampling]. Accepted values are in the range [0,1]. Defaults to 1.0, meaning no telemetry is sampled out. | + + #### Azure monitor OpenTelemetry Exporter configurations @@ -123,12 +105,12 @@ Samples are available [here][samples] to demonstrate how to utilize the above co [exporter_configuration_docs]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/monitor/azure-monitor-opentelemetry-exporter#configuration [logging_level]: https://docs.python.org/3/library/logging.html#levels [logger_name_hierarchy_doc]: https://docs.python.org/3/library/logging.html#logger-objects +[ot_env_vars]: https://opentelemetry.io/docs/reference/specification/sdk-environment-variables/ [ot_instrumentations]: https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation [ot_metric_reader]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#metricreader [ot_python_docs]: https://opentelemetry.io/docs/instrumentation/python/ [ot_sdk_python]: https://github.com/open-telemetry/opentelemetry-python [ot_sdk_python_metric_reader]: https://opentelemetry-python.readthedocs.io/en/stable/sdk/metrics.export.html#opentelemetry.sdk.metrics.export.MetricReader -[ot_sdk_python_resource]: https://github.com/open-telemetry/opentelemetry-python/blob/main/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py#L153 [ot_sdk_python_view_examples]: https://github.com/open-telemetry/opentelemetry-python/tree/main/docs/examples/metrics/views [ot_instrumentation_django]: https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-django [ot_instrumentation_django_version]: https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/opentelemetry-instrumentation-django/src/opentelemetry/instrumentation/django/package.py#L16 diff --git a/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py b/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py index fed4b639..47873cbc 100644 --- a/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py +++ b/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_configure.py @@ -4,22 +4,14 @@ # license information. # -------------------------------------------------------------------------- from logging import getLogger -from typing import Any, Dict +from typing import Dict from azure.monitor.opentelemetry._constants import ( DISABLE_LOGGING_ARG, DISABLE_METRICS_ARG, DISABLE_TRACING_ARG, - EXCLUDE_INSTRUMENTATIONS_ARG, - INSTRUMENTATION_CONFIG_ARG, - LOGGER_NAME_ARG, LOGGING_EXPORT_INTERVAL_MS_ARG, - LOGGING_LEVEL_ARG, - METRIC_READERS_ARG, - RESOURCE_ARG, SAMPLING_RATIO_ARG, - TRACING_EXPORT_INTERVAL_MS_ARG, - VIEWS_ARG, ) from azure.monitor.opentelemetry._types import ConfigurationValue from azure.monitor.opentelemetry.exporter import ( @@ -39,7 +31,6 @@ from opentelemetry.sdk._logs.export import BatchLogRecordProcessor from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.trace import get_tracer_provider, set_tracer_provider @@ -59,30 +50,13 @@ ) -InstrumentationConfig = Dict[str, Dict[str, Any]] - - def configure_azure_monitor(**kwargs) -> None: """ This function works as a configuration layer that allows the end user to configure OpenTelemetry and Azure monitor components. The configuration can be done via arguments passed to this function. :keyword str connection_string: Connection string for your Application Insights resource. - :keyword Sequence[str] exclude_instrumentations: Specifies instrumentations you want to disable. - :keyword Resource resource: Specified the OpenTelemetry [resource][opentelemetry_spec_resource] associated with your application. - :keyword bool disable_logging: If set to `True`, disables collection and export of logging telemetry. Defaults to `False`. - :keyword bool disable_metrics: If set to `True`, disables collection and export of metric telemetry. Defaults to `False`. - :keyword bool disable_tracing: If set to `True`, disables collection and export of distributed tracing telemetry. Defaults to `False`. - :keyword int logging_level: Specifies the logging of the logs you would like to collect for your logging pipeline. - :keyword str logger_name: Specifies the logger name under which logging will be instrumented. Defaults to "" which corresponds to the root logger. - :keyword int logging_export_interval_ms: Specifies the logging export interval in milliseconds. Defaults to 5000. - :keyword Sequence[MetricReader] metric_readers: Specifies the metric readers that you would like to use for your metric pipeline. - :keyword Sequence[View] views: Specifies the list of views to configure for the metric pipeline. - :keyword float sampling_ratio: Specifies the ratio of distributed tracing telemetry to be sampled. Accepted values are in the range [0,1]. Defaults to 1.0, meaning no telemetry is sampled out. - :keyword int tracing_export_interval_ms: Specifies the distributed tracing export interval in milliseconds. Defaults to 5000. - :keyword InstrumentationConfig instrumentation_config: Specifies a dictionary of kwargs that will be applied to instrumentation configuration. You can specify which instrumentation you want to - configure by name in the key field and value as a dictionary representing `kwargs` for the corresponding instrumentation. - Refer to the `Supported Library` section of https://github.com/microsoft/ApplicationInsights-Python/tree/main/azure-monitor-opentelemetry#officially-supported-instrumentations for the list of suppoprted library names. + :keyword ManagedIdentityCredential/ClientSecretCredential credential: Token credential, such as ManagedIdentityCredential or ClientSecretCredential, used for Azure Active Directory (AAD) authentication. Defaults to None. :keyword bool disable_offline_storage: Boolean value to determine whether to disable storing failed telemetry records for retry. Defaults to `False`. :keyword str storage_directory: Storage directory in which to store retry files. Defaults to `/Microsoft/AzureMonitor/opentelemetry-python-`. :rtype: None @@ -94,57 +68,41 @@ def configure_azure_monitor(**kwargs) -> None: disable_logging = configurations[DISABLE_LOGGING_ARG] disable_metrics = configurations[DISABLE_METRICS_ARG] - resource = None - if not disable_logging or not disable_tracing or not disable_metrics: - resource = _get_resource(configurations) - # Setup tracing pipeline if not disable_tracing: - _setup_tracing(resource, configurations) + _setup_tracing(configurations) # Setup logging pipeline if not disable_logging: - _setup_logging(resource, configurations) + _setup_logging(configurations) # Setup metrics pipeline if not disable_metrics: - _setup_metrics(resource, configurations) + _setup_metrics(configurations) # Setup instrumentations # Instrumentations need to be setup last so to use the global providers # instanstiated in the other setup steps - _setup_instrumentations(configurations) - + _setup_instrumentations() -def _get_resource(configurations: Dict[str, ConfigurationValue]) -> Resource: - return configurations.get(RESOURCE_ARG, Resource.create()) - -def _setup_tracing( - resource: Resource, configurations: Dict[str, ConfigurationValue] -): +def _setup_tracing(configurations: Dict[str, ConfigurationValue]): sampling_ratio = configurations[SAMPLING_RATIO_ARG] - tracing_export_interval_ms = configurations[TRACING_EXPORT_INTERVAL_MS_ARG] tracer_provider = TracerProvider( sampler=ApplicationInsightsSampler(sampling_ratio=sampling_ratio), - resource=resource, ) set_tracer_provider(tracer_provider) trace_exporter = AzureMonitorTraceExporter(**configurations) span_processor = BatchSpanProcessor( trace_exporter, - schedule_delay_millis=tracing_export_interval_ms, ) get_tracer_provider().add_span_processor(span_processor) -def _setup_logging( - resource: Resource, configurations: Dict[str, ConfigurationValue] -): - logger_name = configurations[LOGGER_NAME_ARG] - logging_level = configurations[LOGGING_LEVEL_ARG] +def _setup_logging(configurations: Dict[str, ConfigurationValue]): + # TODO: Remove after upgrading to OTel SDK 1.18 logging_export_interval_ms = configurations[LOGGING_EXPORT_INTERVAL_MS_ARG] - logger_provider = LoggerProvider(resource=resource) + logger_provider = LoggerProvider() set_logger_provider(logger_provider) log_exporter = AzureMonitorLogExporter(**configurations) log_record_processor = BatchLogRecordProcessor( @@ -152,39 +110,25 @@ def _setup_logging( schedule_delay_millis=logging_export_interval_ms, ) get_logger_provider().add_log_record_processor(log_record_processor) - handler = LoggingHandler( - level=logging_level, logger_provider=get_logger_provider() - ) - getLogger(logger_name).addHandler(handler) + handler = LoggingHandler(logger_provider=get_logger_provider()) + getLogger().addHandler(handler) -def _setup_metrics( - resource: Resource, configurations: Dict[str, ConfigurationValue] -): - views = configurations[VIEWS_ARG] - metric_readers = configurations[METRIC_READERS_ARG] +def _setup_metrics(configurations: Dict[str, ConfigurationValue]): metric_exporter = AzureMonitorMetricExporter(**configurations) reader = PeriodicExportingMetricReader(metric_exporter) meter_provider = MeterProvider( - metric_readers=[reader] + metric_readers, - resource=resource, - views=views, + metric_readers=[reader], ) set_meter_provider(meter_provider) -def _setup_instrumentations(configurations: Dict[str, ConfigurationValue]): - exclude_instrumentations = configurations[EXCLUDE_INSTRUMENTATIONS_ARG] - instrumentation_configs = configurations[INSTRUMENTATION_CONFIG_ARG] - +def _setup_instrumentations(): # use pkg_resources for now until https://github.com/open-telemetry/opentelemetry-python/pull/3168 is merged for entry_point in iter_entry_points("opentelemetry_instrumentor"): lib_name = entry_point.name if lib_name not in _SUPPORTED_INSTRUMENTED_LIBRARIES: continue - if lib_name in exclude_instrumentations: - _logger.debug("Instrumentation excluded for library %s", lib_name) - continue try: # Check if dependent libraries/version are installed conflict = get_dist_dependency_conflicts(entry_point.dist) @@ -197,11 +141,8 @@ def _setup_instrumentations(configurations: Dict[str, ConfigurationValue]): continue # Load the instrumentor via entrypoint instrumentor: BaseInstrumentor = entry_point.load() - # Call instrument() with configuration - config = instrumentation_configs.get(lib_name, {}) # tell instrumentation to not run dep checks again as we already did it above - config["skip_dep_check"] = True - instrumentor().instrument(**config) + instrumentor().instrument(skip_dep_check=True) except Exception as ex: _logger.warning( "Exception occured when instrumenting: %s.", diff --git a/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_constants.py b/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_constants.py index 2489b772..7fe1b0dd 100644 --- a/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_constants.py +++ b/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_constants.py @@ -16,20 +16,11 @@ # --------------------Configuration------------------------------------------ CONNECTION_STRING_ARG = "connection_string" -EXCLUDE_INSTRUMENTATIONS_ARG = "exclude_instrumentations" -RESOURCE_ARG = "resource" DISABLE_LOGGING_ARG = "disable_logging" DISABLE_METRICS_ARG = "disable_metrics" DISABLE_TRACING_ARG = "disable_tracing" -# TODO: Consider Log Level to match env var -LOGGING_LEVEL_ARG = "logging_level" -LOGGER_NAME_ARG = "logger_name" LOGGING_EXPORT_INTERVAL_MS_ARG = "logging_export_interval_ms" -METRIC_READERS_ARG = "metric_readers" -VIEWS_ARG = "views" SAMPLING_RATIO_ARG = "sampling_ratio" -TRACING_EXPORT_INTERVAL_MS_ARG = "tracing_export_interval_ms" -INSTRUMENTATION_CONFIG_ARG = "instrumentation_config" # --------------------Diagnostic/status logging------------------------------ diff --git a/azure-monitor-opentelemetry/azure/monitor/opentelemetry/util/configurations.py b/azure-monitor-opentelemetry/azure/monitor/opentelemetry/util/configurations.py index 5fa17b8a..270b633a 100644 --- a/azure-monitor-opentelemetry/azure/monitor/opentelemetry/util/configurations.py +++ b/azure-monitor-opentelemetry/azure/monitor/opentelemetry/util/configurations.py @@ -4,7 +4,7 @@ # license information. # -------------------------------------------------------------------------- -from logging import NOTSET, getLogger +from logging import getLogger from os import environ from typing import Dict @@ -12,15 +12,8 @@ DISABLE_LOGGING_ARG, DISABLE_METRICS_ARG, DISABLE_TRACING_ARG, - EXCLUDE_INSTRUMENTATIONS_ARG, - INSTRUMENTATION_CONFIG_ARG, - LOGGER_NAME_ARG, LOGGING_EXPORT_INTERVAL_MS_ARG, - LOGGING_LEVEL_ARG, - METRIC_READERS_ARG, SAMPLING_RATIO_ARG, - TRACING_EXPORT_INTERVAL_MS_ARG, - VIEWS_ARG, ) from azure.monitor.opentelemetry._types import ConfigurationValue from opentelemetry.environment_variables import ( @@ -31,9 +24,10 @@ from opentelemetry.sdk.environment_variables import OTEL_TRACES_SAMPLER_ARG _INVALID_FLOAT_MESSAGE = "Value of %s must be a float. Defaulting to %s: %s" +_INVALID_INT_MESSAGE = "Value of %s must be a integer. Defaulting to %s: %s" -# Speced out but unused by OTel SDK as of 1.15.0 +# Speced out but unused by OTel SDK as of 1.17.0 LOGGING_EXPORT_INTERVAL_MS_ENV_VAR = "OTEL_BLRP_SCHEDULE_DELAY" # TODO: remove when sampler uses env var instead SAMPLING_RATIO_ENV_VAR = OTEL_TRACES_SAMPLER_ARG @@ -48,18 +42,11 @@ def _get_configurations(**kwargs) -> Dict[str, ConfigurationValue]: for key, val in kwargs.items(): configurations[key] = val - _default_exclude_instrumentations(configurations) _default_disable_logging(configurations) _default_disable_metrics(configurations) _default_disable_tracing(configurations) - _default_logging_level(configurations) - _default_logger_name(configurations) _default_logging_export_interval_ms(configurations) - _default_metric_readers(configurations) - _default_views(configurations) _default_sampling_ratio(configurations) - _default_tracing_export_interval_ms(configurations) - _default_instrumentation_config(configurations) # TODO: remove when validation added to BLRP if configurations[LOGGING_EXPORT_INTERVAL_MS_ARG] <= 0: @@ -70,83 +57,51 @@ def _get_configurations(**kwargs) -> Dict[str, ConfigurationValue]: return configurations -def _default_exclude_instrumentations(configurations): - if EXCLUDE_INSTRUMENTATIONS_ARG not in configurations: - configurations[EXCLUDE_INSTRUMENTATIONS_ARG] = [] - - def _default_disable_logging(configurations): - if DISABLE_LOGGING_ARG not in configurations: - default = False - if OTEL_LOGS_EXPORTER in environ: - if environ[OTEL_LOGS_EXPORTER].lower().strip() == "none": - default = True - configurations[DISABLE_LOGGING_ARG] = default + default = False + if OTEL_LOGS_EXPORTER in environ: + if environ[OTEL_LOGS_EXPORTER].lower().strip() == "none": + default = True + configurations[DISABLE_LOGGING_ARG] = default def _default_disable_metrics(configurations): - if DISABLE_METRICS_ARG not in configurations: - default = False - if OTEL_METRICS_EXPORTER in environ: - if environ[OTEL_METRICS_EXPORTER].lower().strip() == "none": - default = True - configurations[DISABLE_METRICS_ARG] = default + default = False + if OTEL_METRICS_EXPORTER in environ: + if environ[OTEL_METRICS_EXPORTER].lower().strip() == "none": + default = True + configurations[DISABLE_METRICS_ARG] = default def _default_disable_tracing(configurations): - if DISABLE_TRACING_ARG not in configurations: - default = False - if OTEL_TRACES_EXPORTER in environ: - if environ[OTEL_TRACES_EXPORTER].lower().strip() == "none": - default = True - configurations[DISABLE_TRACING_ARG] = default - - -def _default_logging_level(configurations): - if LOGGING_LEVEL_ARG not in configurations: - configurations[LOGGING_LEVEL_ARG] = NOTSET - - -def _default_logger_name(configurations): - if LOGGER_NAME_ARG not in configurations: - configurations[LOGGER_NAME_ARG] = "" + default = False + if OTEL_TRACES_EXPORTER in environ: + if environ[OTEL_TRACES_EXPORTER].lower().strip() == "none": + default = True + configurations[DISABLE_TRACING_ARG] = default def _default_logging_export_interval_ms(configurations): - if LOGGING_EXPORT_INTERVAL_MS_ARG not in configurations: - configurations[LOGGING_EXPORT_INTERVAL_MS_ARG] = 5000 - - -def _default_metric_readers(configurations): - if METRIC_READERS_ARG not in configurations: - configurations[METRIC_READERS_ARG] = [] - - -def _default_views(configurations): - if VIEWS_ARG not in configurations: - configurations[VIEWS_ARG] = () + default = 5000 + if LOGGING_EXPORT_INTERVAL_MS_ENV_VAR in environ: + try: + default = int(environ[LOGGING_EXPORT_INTERVAL_MS_ENV_VAR]) + except ValueError as e: + _logger.error( + _INVALID_INT_MESSAGE + % (LOGGING_EXPORT_INTERVAL_MS_ENV_VAR, default, e) + ) + configurations[LOGGING_EXPORT_INTERVAL_MS_ARG] = default # TODO: remove when sampler uses env var instead def _default_sampling_ratio(configurations): - if SAMPLING_RATIO_ARG not in configurations: - default = 1.0 - if SAMPLING_RATIO_ENV_VAR in environ: - try: - default = float(environ[SAMPLING_RATIO_ENV_VAR]) - except ValueError as e: - _logger.error( - _INVALID_FLOAT_MESSAGE - % (SAMPLING_RATIO_ENV_VAR, default, e) - ) - configurations[SAMPLING_RATIO_ARG] = default - - -def _default_tracing_export_interval_ms(configurations): - if TRACING_EXPORT_INTERVAL_MS_ARG not in configurations: - configurations[TRACING_EXPORT_INTERVAL_MS_ARG] = None - - -def _default_instrumentation_config(configurations): - if INSTRUMENTATION_CONFIG_ARG not in configurations: - configurations[INSTRUMENTATION_CONFIG_ARG] = {} + default = 1.0 + if SAMPLING_RATIO_ENV_VAR in environ: + try: + default = float(environ[SAMPLING_RATIO_ENV_VAR]) + except ValueError as e: + _logger.error( + _INVALID_FLOAT_MESSAGE % (SAMPLING_RATIO_ENV_VAR, default, e) + ) + configurations[SAMPLING_RATIO_ARG] = default diff --git a/azure-monitor-opentelemetry/samples/logging/correlated_logs.py b/azure-monitor-opentelemetry/samples/logging/correlated_logs.py index e37cbddc..43d77540 100644 --- a/azure-monitor-opentelemetry/samples/logging/correlated_logs.py +++ b/azure-monitor-opentelemetry/samples/logging/correlated_logs.py @@ -11,10 +11,6 @@ configure_azure_monitor( connection_string="", - logger_name=__name__, - logging_level=WARNING, - disable_metrics=True, - disable_tracing=True, ) logger = getLogger(__name__) diff --git a/azure-monitor-opentelemetry/samples/logging/custom_properties.py b/azure-monitor-opentelemetry/samples/logging/custom_properties.py index 76d88a48..4cc9f19f 100644 --- a/azure-monitor-opentelemetry/samples/logging/custom_properties.py +++ b/azure-monitor-opentelemetry/samples/logging/custom_properties.py @@ -10,10 +10,6 @@ configure_azure_monitor( connection_string="", - logger_name=__name__, - logging_level=DEBUG, - disable_metrics=True, - disable_tracing=True, ) logger = getLogger(__name__) diff --git a/azure-monitor-opentelemetry/samples/logging/exception_logs.py b/azure-monitor-opentelemetry/samples/logging/exception_logs.py index d53cff6a..ff566adc 100644 --- a/azure-monitor-opentelemetry/samples/logging/exception_logs.py +++ b/azure-monitor-opentelemetry/samples/logging/exception_logs.py @@ -10,10 +10,6 @@ configure_azure_monitor( connection_string="", - logger_name=__name__, - logging_level=WARNING, - disable_metrics=True, - disable_tracing=True, ) logger = getLogger(__name__) diff --git a/azure-monitor-opentelemetry/samples/logging/logs_with_traces.py b/azure-monitor-opentelemetry/samples/logging/logs_with_traces.py index ca3c5660..a646100d 100644 --- a/azure-monitor-opentelemetry/samples/logging/logs_with_traces.py +++ b/azure-monitor-opentelemetry/samples/logging/logs_with_traces.py @@ -4,20 +4,17 @@ # license information. # -------------------------------------------------------------------------- -from logging import WARNING, getLogger +from logging import INFO, getLogger import flask from azure.monitor.opentelemetry import configure_azure_monitor configure_azure_monitor( connection_string="", - logger_name=__name__, - logging_level=WARNING, - disable_metrics=True, - tracing_export_interval_ms=15000, ) logger = getLogger(__name__) +logger.setLevel(INFO) app = flask.Flask(__name__) @@ -36,16 +33,5 @@ def error_log(): return message -@app.route("/error_log") -def error_log(): - message = "Correlated error log" - logger.error(message) - return message - - if __name__ == "__main__": app.run(host="localhost", port=8080) - - logger.info("Correlated info log") - logger.warning("Correlated warning log") - logger.error("Correlated error log") diff --git a/azure-monitor-opentelemetry/samples/logging/simple.py b/azure-monitor-opentelemetry/samples/logging/simple.py index ee0f175c..60085a1c 100644 --- a/azure-monitor-opentelemetry/samples/logging/simple.py +++ b/azure-monitor-opentelemetry/samples/logging/simple.py @@ -11,16 +11,6 @@ configure_azure_monitor( connection_string="", - logger_name=__name__, - logging_level=WARNING, - resource=Resource.create( - { - ResourceAttributes.SERVICE_NAME: "simple_service", - ResourceAttributes.SERVICE_INSTANCE_ID: "simple_logging_instance", - } - ), - disable_metrics=True, - disable_tracing=True, ) logger = getLogger(__name__) diff --git a/azure-monitor-opentelemetry/samples/metrics/attributes.py b/azure-monitor-opentelemetry/samples/metrics/attributes.py index 6496ddab..95766db5 100644 --- a/azure-monitor-opentelemetry/samples/metrics/attributes.py +++ b/azure-monitor-opentelemetry/samples/metrics/attributes.py @@ -7,8 +7,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_tracing=True, ) attribute_set1 = {"key1": "val1"} diff --git a/azure-monitor-opentelemetry/samples/metrics/instruments.py b/azure-monitor-opentelemetry/samples/metrics/instruments.py index 82bd5d11..663c54bf 100644 --- a/azure-monitor-opentelemetry/samples/metrics/instruments.py +++ b/azure-monitor-opentelemetry/samples/metrics/instruments.py @@ -10,14 +10,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_tracing=True, - resource=Resource.create( - { - ResourceAttributes.SERVICE_NAME: "metric_service", - ResourceAttributes.SERVICE_INSTANCE_ID: "instrument_instance", - } - ), ) diff --git a/azure-monitor-opentelemetry/samples/metrics/views.py b/azure-monitor-opentelemetry/samples/metrics/views.py deleted file mode 100644 index b81b1186..00000000 --- a/azure-monitor-opentelemetry/samples/metrics/views.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. -from azure.monitor.opentelemetry import configure_azure_monitor -from opentelemetry import metrics -from opentelemetry.sdk.metrics import Counter -from opentelemetry.sdk.metrics.view import View - -# 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( - instrument_type=Counter, - instrument_name="my.counter", - name="my.counter.total", -) - -# Configure Azure monitor collection telemetry pipeline -configure_azure_monitor( - connection_string="", - disable_logging=True, - disable_tracing=True, - metrics_export_interval_millis=30000, - views=[change_metric_name_view], -) - -meter = metrics.get_meter_provider().get_meter("view-name-change") -my_counter = meter.create_counter("my.counter") -my_counter.add(100) - -input() diff --git a/azure-monitor-opentelemetry/samples/tracing/db_psycopg2.py b/azure-monitor-opentelemetry/samples/tracing/db_psycopg2.py index 5811b6ec..ae7be561 100644 --- a/azure-monitor-opentelemetry/samples/tracing/db_psycopg2.py +++ b/azure-monitor-opentelemetry/samples/tracing/db_psycopg2.py @@ -9,9 +9,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_metrics=True, - tracing_export_interval_ms=15000, ) # Database calls using the psycopg2 library will be automatically captured diff --git a/azure-monitor-opentelemetry/samples/tracing/django/sample/example/views.py b/azure-monitor-opentelemetry/samples/tracing/django/sample/example/views.py index 6906c9d7..eb5a25aa 100644 --- a/azure-monitor-opentelemetry/samples/tracing/django/sample/example/views.py +++ b/azure-monitor-opentelemetry/samples/tracing/django/sample/example/views.py @@ -10,9 +10,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_metrics=True, - tracing_export_interval_ms=15000, ) diff --git a/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py b/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py index f7a0f4ba..123890e0 100644 --- a/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py +++ b/azure-monitor-opentelemetry/samples/tracing/http_fastapi.py @@ -9,14 +9,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_metrics=True, - instrumentation_config={ - "fastapi": { - "excluded_urls": "http://127.0.0.1:8000/exclude", - } - }, - tracing_export_interval_ms=15000, ) app = fastapi.FastAPI() diff --git a/azure-monitor-opentelemetry/samples/tracing/http_flask.py b/azure-monitor-opentelemetry/samples/tracing/http_flask.py index a492ba5c..06dc5c3c 100644 --- a/azure-monitor-opentelemetry/samples/tracing/http_flask.py +++ b/azure-monitor-opentelemetry/samples/tracing/http_flask.py @@ -9,14 +9,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_metrics=True, - instrumentation_config={ - "flask": { - "excluded_urls": "http://localhost:8080/ignore", - } - }, - tracing_export_interval_ms=15000, ) app = flask.Flask(__name__) diff --git a/azure-monitor-opentelemetry/samples/tracing/http_requests.py b/azure-monitor-opentelemetry/samples/tracing/http_requests.py index 64b4de49..26f94249 100644 --- a/azure-monitor-opentelemetry/samples/tracing/http_requests.py +++ b/azure-monitor-opentelemetry/samples/tracing/http_requests.py @@ -14,14 +14,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_metrics=True, - instrumentation_config={ - "requests": { - "excluded_urls": "http://example.com", - } - }, - tracing_export_interval_ms=15000, ) tracer = trace.get_tracer(__name__) diff --git a/azure-monitor-opentelemetry/samples/tracing/http_urllib.py b/azure-monitor-opentelemetry/samples/tracing/http_urllib.py index 40896f4b..af260666 100644 --- a/azure-monitor-opentelemetry/samples/tracing/http_urllib.py +++ b/azure-monitor-opentelemetry/samples/tracing/http_urllib.py @@ -14,9 +14,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_metrics=True, - tracing_export_interval_ms=15000, ) tracer = trace.get_tracer(__name__) diff --git a/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py b/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py index 96ed3f40..92446121 100644 --- a/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py +++ b/azure-monitor-opentelemetry/samples/tracing/http_urllib3.py @@ -14,9 +14,6 @@ # Configure Azure monitor collection telemetry pipeline configure_azure_monitor( connection_string="", - disable_logging=True, - disable_metrics=True, - tracing_export_interval_ms=15000, ) http = urllib3.PoolManager() diff --git a/azure-monitor-opentelemetry/samples/tracing/manual.py b/azure-monitor-opentelemetry/samples/tracing/manual.py index 39386429..47649f8d 100644 --- a/azure-monitor-opentelemetry/samples/tracing/manual.py +++ b/azure-monitor-opentelemetry/samples/tracing/manual.py @@ -9,9 +9,6 @@ configure_azure_monitor( connection_string="", - tracing_export_interval_ms=15000, - disable_logging=True, - disable_metrics=True, ) engine = create_engine("sqlite:///:memory:") diff --git a/azure-monitor-opentelemetry/samples/tracing/sampling.py b/azure-monitor-opentelemetry/samples/tracing/sampling.py index 7cd2831a..a89bc4e6 100644 --- a/azure-monitor-opentelemetry/samples/tracing/sampling.py +++ b/azure-monitor-opentelemetry/samples/tracing/sampling.py @@ -7,14 +7,12 @@ from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry import trace +# Set the OTEL_TRACES_SAMPLER_ARG environment variable to 0.1 +# Sampling ratio of between 0 and 1 inclusive +# 0.1 means approximately 10% of your traces are sent + configure_azure_monitor( connection_string="", - # Sampling ratio of between 0 and 1 inclusive - # 0.1 means approximately 10% of your traces are sent - sampling_ratio=0.1, - tracing_export_interval_ms=15000, - disable_logging=True, - disable_metrics=True, ) tracer = trace.get_tracer(__name__) diff --git a/azure-monitor-opentelemetry/samples/tracing/simple.py b/azure-monitor-opentelemetry/samples/tracing/simple.py index 37d5d32c..ef7e0865 100644 --- a/azure-monitor-opentelemetry/samples/tracing/simple.py +++ b/azure-monitor-opentelemetry/samples/tracing/simple.py @@ -10,15 +10,6 @@ configure_azure_monitor( connection_string="", - resource=Resource.create( - { - ResourceAttributes.SERVICE_NAME: "simple_service", - ResourceAttributes.SERVICE_INSTANCE_ID: "simple_tracing_instance", - } - ), - tracing_export_interval_ms=15000, - disable_logging=True, - disable_metrics=True, ) tracer = trace.get_tracer(__name__) diff --git a/azure-monitor-opentelemetry/tests/configuration/test_configure.py b/azure-monitor-opentelemetry/tests/configuration/test_configure.py index 667e89ad..a313e634 100644 --- a/azure-monitor-opentelemetry/tests/configuration/test_configure.py +++ b/azure-monitor-opentelemetry/tests/configuration/test_configure.py @@ -17,7 +17,6 @@ from azure.monitor.opentelemetry._configure import ( _SUPPORTED_INSTRUMENTED_LIBRARIES, - _get_resource, _setup_instrumentations, _setup_logging, _setup_metrics, @@ -39,12 +38,8 @@ class TestConfigure(unittest.TestCase): @patch( "azure.monitor.opentelemetry._configure._setup_tracing", ) - @patch( - "azure.monitor.opentelemetry._configure._get_resource", - ) def test_configure_azure_monitor( self, - resource_mock, tracing_mock, logging_mock, metrics_mock, @@ -52,28 +47,12 @@ def test_configure_azure_monitor( ): kwargs = { "connection_string": "test_cs", - "exclude_instrumentations": [], - "disable_tracing": False, - "disable_logging": False, - "disable_metrics": False, - "logging_export_interval_ms": 10000, - "logging_level": "test_logging_level", - "logger_name": "test_logger_name", - "resource": "test_resource", - "sampling_ratio": 0.5, - "tracing_export_interval_ms": 15000, - "metric_readers": "test_metric_readers", - "views": "test_views", - "instrumentation_config": [], } - resource_init_mock = Mock() - resource_mock.return_value = resource_init_mock configure_azure_monitor(**kwargs) - resource_mock.assert_called_once_with(kwargs) - tracing_mock.assert_called_once_with(resource_init_mock, kwargs) - logging_mock.assert_called_once_with(resource_init_mock, kwargs) - metrics_mock.assert_called_once_with(resource_init_mock, kwargs) - instrumentation_mock.assert_called_once_with(kwargs) + tracing_mock.assert_called_once() + logging_mock.assert_called_once() + metrics_mock.assert_called_once() + instrumentation_mock.assert_called_once_with() @patch( "azure.monitor.opentelemetry._configure._setup_instrumentations", @@ -88,40 +67,28 @@ def test_configure_azure_monitor( "azure.monitor.opentelemetry._configure._setup_tracing", ) @patch( - "azure.monitor.opentelemetry._configure._get_resource", + "azure.monitor.opentelemetry._configure._get_configurations", ) def test_configure_azure_monitor_disable_tracing( self, - resource_mock, + config_mock, tracing_mock, logging_mock, metrics_mock, instrumentation_mock, ): - kwargs = { + configurations = { "connection_string": "test_cs", - "exclude_instrumentations": [], "disable_tracing": True, "disable_logging": False, "disable_metrics": False, - "logging_export_interval_ms": 10000, - "logging_level": "test_logging_level", - "logger_name": "test_logger_name", - "resource": "test_resource", - "sampling_ratio": 0.5, - "tracing_export_interval_ms": 15000, - "metric_readers": [], - "views": "test_views", - "instrumentation_config": [], } - resource_init_mock = Mock() - resource_mock.return_value = resource_init_mock - configure_azure_monitor(**kwargs) - resource_mock.assert_called_once_with(kwargs) + config_mock.return_value = configurations + configure_azure_monitor() tracing_mock.assert_not_called() - logging_mock.assert_called_once_with(resource_init_mock, kwargs) - metrics_mock.assert_called_once_with(resource_init_mock, kwargs) - instrumentation_mock.assert_called_once_with(kwargs) + logging_mock.assert_called_once_with(configurations) + metrics_mock.assert_called_once_with(configurations) + instrumentation_mock.assert_called_once_with() @patch( "azure.monitor.opentelemetry._configure._setup_instrumentations", @@ -136,40 +103,28 @@ def test_configure_azure_monitor_disable_tracing( "azure.monitor.opentelemetry._configure._setup_tracing", ) @patch( - "azure.monitor.opentelemetry._configure._get_resource", + "azure.monitor.opentelemetry._configure._get_configurations", ) def test_configure_azure_monitor_disable_logging( self, - resource_mock, + config_mock, tracing_mock, logging_mock, metrics_mock, instrumentation_mock, ): - kwargs = { + configurations = { "connection_string": "test_cs", - "exclude_instrumentations": [], "disable_tracing": False, "disable_logging": True, "disable_metrics": False, - "logging_export_interval_ms": 10000, - "logging_level": "test_logging_level", - "logger_name": "test_logger_name", - "resource": "test_resource", - "sampling_ratio": 0.5, - "tracing_export_interval_ms": 15000, - "metric_readers": [], - "views": "test_views", - "instrumentation_config": [], } - resource_init_mock = Mock() - resource_mock.return_value = resource_init_mock - configure_azure_monitor(**kwargs) - resource_mock.assert_called_once_with(kwargs) - tracing_mock.assert_called_once_with(resource_init_mock, kwargs) + config_mock.return_value = configurations + configure_azure_monitor() + tracing_mock.assert_called_once_with(configurations) logging_mock.assert_not_called() - metrics_mock.assert_called_once_with(resource_init_mock, kwargs) - instrumentation_mock.assert_called_once_with(kwargs) + metrics_mock.assert_called_once_with(configurations) + instrumentation_mock.assert_called_once_with() @patch( "azure.monitor.opentelemetry._configure._setup_instrumentations", @@ -184,53 +139,28 @@ def test_configure_azure_monitor_disable_logging( "azure.monitor.opentelemetry._configure._setup_tracing", ) @patch( - "azure.monitor.opentelemetry._configure._get_resource", + "azure.monitor.opentelemetry._configure._get_configurations", ) def test_configure_azure_monitor_disable_metrics( self, - resource_mock, + config_mock, tracing_mock, logging_mock, metrics_mock, instrumentation_mock, ): - kwargs = { + configurations = { "connection_string": "test_cs", - "exclude_instrumentations": [], "disable_tracing": False, "disable_logging": False, "disable_metrics": True, - "logging_export_interval_ms": 10000, - "logging_level": "test_logging_level", - "logger_name": "test_logger_name", - "resource": "test_resource", - "sampling_ratio": 0.5, - "tracing_export_interval_ms": 15000, - "metric_readers": [], - "views": "test_views", - "instrumentation_config": [], } - resource_init_mock = Mock() - resource_mock.return_value = resource_init_mock - configure_azure_monitor(**kwargs) - resource_mock.assert_called_once_with(kwargs) - tracing_mock.assert_called_once_with(resource_init_mock, kwargs) - logging_mock.assert_called_once_with(resource_init_mock, kwargs) + config_mock.return_value = configurations + configure_azure_monitor() + tracing_mock.assert_called_once_with(configurations) + logging_mock.assert_called_once_with(configurations) metrics_mock.assert_not_called() - instrumentation_mock.assert_called_once_with(kwargs) - - def test_get_resource(self): - configuration = {"resource": "test_resource"} - res = _get_resource(configuration) - self.assertEqual(res, "test_resource") - - @patch( - "azure.monitor.opentelemetry._configure.Resource", - ) - def test_get_resource_default(self, resource_mock): - configuration = {} - _get_resource(configuration) - resource_mock.create.assert_called_once_with() + instrumentation_mock.assert_called_once_with() @patch( "azure.monitor.opentelemetry._configure.BatchSpanProcessor", @@ -260,7 +190,6 @@ def test_setup_tracing( trace_exporter_mock, bsp_mock, ): - resource_mock = Mock() sampler_init_mock = Mock() sampler_mock.return_value = sampler_init_mock tp_init_mock = Mock() @@ -273,22 +202,17 @@ def test_setup_tracing( configurations = { "connection_string": "test_cs", - "disable_tracing": False, "sampling_ratio": 0.5, - "tracing_export_interval_ms": 15000, } - _setup_tracing(resource_mock, configurations) + _setup_tracing(configurations) sampler_mock.assert_called_once_with(sampling_ratio=0.5) tp_mock.assert_called_once_with( - resource=resource_mock, sampler=sampler_init_mock, ) set_tracer_provider_mock.assert_called_once_with(tp_init_mock) get_tracer_provider_mock.assert_called() - trace_exporter_mock.assert_called_once() - bsp_mock.assert_called_once_with( - trace_exp_init_mock, schedule_delay_millis=15000 - ) + trace_exporter_mock.assert_called_once_with(**configurations) + bsp_mock.assert_called_once_with(trace_exp_init_mock) tp_init_mock.add_span_processor.assert_called_once_with(bsp_init_mock) @patch( @@ -323,8 +247,6 @@ def test_setup_logging( logging_handler_mock, get_logger_mock, ): - resource_mock = Mock() - lp_init_mock = Mock() lp_mock.return_value = lp_init_mock get_logger_provider_mock.return_value = lp_init_mock @@ -339,17 +261,14 @@ def test_setup_logging( configurations = { "connection_string": "test_cs", - "disable_logging": False, "logging_export_interval_ms": 10000, - "logging_level": "test_logging_level", - "logger_name": "test_logger_name", } - _setup_logging(resource_mock, configurations) + _setup_logging(configurations) - lp_mock.assert_called_once_with(resource=resource_mock) + lp_mock.assert_called_once_with() set_logger_provider_mock.assert_called_once_with(lp_init_mock) get_logger_provider_mock.assert_called() - log_exporter_mock.assert_called_once() + log_exporter_mock.assert_called_once_with(**configurations) blrp_mock.assert_called_once_with( log_exp_init_mock, schedule_delay_millis=10000 ) @@ -357,9 +276,9 @@ def test_setup_logging( blrp_init_mock ) logging_handler_mock.assert_called_once_with( - level="test_logging_level", logger_provider=lp_init_mock + logger_provider=lp_init_mock ) - get_logger_mock.assert_called_once_with("test_logger_name") + get_logger_mock.assert_called_once_with() logger_mock.addHandler.assert_called_once_with( logging_handler_init_mock ) @@ -384,7 +303,6 @@ def test_setup_metrics( metric_exporter_mock, reader_mock, ): - resource_mock = Mock() mp_init_mock = Mock() mp_mock.return_value = mp_init_mock metric_exp_init_mock = Mock() @@ -394,47 +312,15 @@ def test_setup_metrics( configurations = { "connection_string": "test_cs", - "disable_metrics": False, - "metric_readers": ["test_reader1", "test_reader2"], - "views": "test_views", } - _setup_metrics(resource_mock, configurations) + _setup_metrics(configurations) mp_mock.assert_called_once_with( - metric_readers=[reader_init_mock, "test_reader1", "test_reader2"], - resource=resource_mock, - views="test_views", + metric_readers=[reader_init_mock], ) set_meter_provider_mock.assert_called_once_with(mp_init_mock) - metric_exporter_mock.assert_called_once() + metric_exporter_mock.assert_called_once_with(**configurations) reader_mock.assert_called_once_with(metric_exp_init_mock) - @patch( - "azure.monitor.opentelemetry._configure.get_dist_dependency_conflicts" - ) - @patch("azure.monitor.opentelemetry._configure.iter_entry_points") - def test_setup_instrumentations( - self, - iter_mock, - dep_mock, - ): - configurations = { - "exclude_instrumentations": [], - "instrumentation_config": {}, - } - ep_mock = Mock() - iter_mock.return_value = [ep_mock] - instrumentor_mock = Mock() - instr_class_mock = Mock() - instr_class_mock.return_value = instrumentor_mock - ep_mock.name = _SUPPORTED_INSTRUMENTED_LIBRARIES[0] - ep_mock.load.return_value = instr_class_mock - dep_mock.return_value = None - _setup_instrumentations(configurations) - iter_mock.assert_called_with("opentelemetry_instrumentor") - dep_mock.assert_called_with(ep_mock.dist) - ep_mock.load.assert_called_once() - instrumentor_mock.instrument.assert_called_once() - @patch( "azure.monitor.opentelemetry._configure.get_dist_dependency_conflicts" ) @@ -444,10 +330,6 @@ def test_setup_instrumentations_lib_not_supported( iter_mock, dep_mock, ): - configurations = { - "exclude_instrumentations": [], - "instrumentation_config": {}, - } ep_mock = Mock() ep2_mock = Mock() iter_mock.return_value = (ep_mock, ep2_mock) @@ -458,37 +340,7 @@ def test_setup_instrumentations_lib_not_supported( ep2_mock.name = _SUPPORTED_INSTRUMENTED_LIBRARIES[1] ep2_mock.load.return_value = instr_class_mock dep_mock.return_value = None - _setup_instrumentations(configurations) - dep_mock.assert_called_with(ep2_mock.dist) - ep_mock.load.assert_not_called() - ep2_mock.load.assert_called_once() - instrumentor_mock.instrument.assert_called_once() - - @patch( - "azure.monitor.opentelemetry._configure.get_dist_dependency_conflicts" - ) - @patch("azure.monitor.opentelemetry._configure.iter_entry_points") - def test_setup_instrumentations_lib_excluded( - self, - iter_mock, - dep_mock, - ): - instr_exclude = _SUPPORTED_INSTRUMENTED_LIBRARIES[0] - configurations = { - "exclude_instrumentations": [instr_exclude], - "instrumentation_config": {}, - } - ep_mock = Mock() - ep2_mock = Mock() - iter_mock.return_value = (ep_mock, ep2_mock) - instrumentor_mock = Mock() - instr_class_mock = Mock() - instr_class_mock.return_value = instrumentor_mock - ep_mock.name = instr_exclude - ep2_mock.name = _SUPPORTED_INSTRUMENTED_LIBRARIES[1] - ep2_mock.load.return_value = instr_class_mock - dep_mock.return_value = None - _setup_instrumentations(configurations) + _setup_instrumentations() dep_mock.assert_called_with(ep2_mock.dist) ep_mock.load.assert_not_called() ep2_mock.load.assert_called_once() @@ -505,10 +357,6 @@ def test_setup_instrumentations_conflict( dep_mock, logger_mock, ): - configurations = { - "exclude_instrumentations": [], - "instrumentation_config": {}, - } ep_mock = Mock() iter_mock.return_value = (ep_mock,) instrumentor_mock = Mock() @@ -517,7 +365,7 @@ def test_setup_instrumentations_conflict( ep_mock.name = _SUPPORTED_INSTRUMENTED_LIBRARIES[0] ep_mock.load.return_value = instr_class_mock dep_mock.return_value = True - _setup_instrumentations(configurations) + _setup_instrumentations() dep_mock.assert_called_with(ep_mock.dist) ep_mock.load.assert_not_called() instrumentor_mock.instrument.assert_not_called() @@ -534,10 +382,6 @@ def test_setup_instrumentations_exception( dep_mock, logger_mock, ): - configurations = { - "exclude_instrumentations": [], - "instrumentation_config": {}, - } ep_mock = Mock() iter_mock.return_value = (ep_mock,) instrumentor_mock = Mock() @@ -546,82 +390,8 @@ def test_setup_instrumentations_exception( ep_mock.name = _SUPPORTED_INSTRUMENTED_LIBRARIES[0] ep_mock.load.side_effect = Exception() dep_mock.return_value = None - _setup_instrumentations(configurations) + _setup_instrumentations() dep_mock.assert_called_with(ep_mock.dist) ep_mock.load.assert_called_once() instrumentor_mock.instrument.assert_not_called() logger_mock.warning.assert_called_once() - - @patch( - "azure.monitor.opentelemetry._configure.get_dist_dependency_conflicts" - ) - @patch("azure.monitor.opentelemetry._configure.iter_entry_points") - def test_setup_instrumentations_custom_configuration( - self, - iter_mock, - dep_mock, - ): - libr_name = _SUPPORTED_INSTRUMENTED_LIBRARIES[0] - configurations = { - "exclude_instrumentations": [], - "instrumentation_config": { - libr_name: { - "test_key": "test_value", - } - }, - } - ep_mock = Mock() - iter_mock.return_value = [ep_mock] - instrumentor_mock = Mock() - instr_class_mock = Mock() - instr_class_mock.return_value = instrumentor_mock - ep_mock.name = libr_name - ep_mock.load.return_value = instr_class_mock - dep_mock.return_value = None - _setup_instrumentations(configurations) - iter_mock.assert_called_with("opentelemetry_instrumentor") - dep_mock.assert_called_with(ep_mock.dist) - ep_mock.load.assert_called_once() - instrumentor_mock.instrument.assert_called_once_with( - **{"test_key": "test_value", "skip_dep_check": True} - ) - - @patch( - "azure.monitor.opentelemetry._configure.get_dist_dependency_conflicts" - ) - @patch("azure.monitor.opentelemetry._configure.iter_entry_points") - def test_setup_instrumentations_custom_configuration_excluded( - self, - iter_mock, - dep_mock, - ): - libr_name = _SUPPORTED_INSTRUMENTED_LIBRARIES[0] - libr_name2 = _SUPPORTED_INSTRUMENTED_LIBRARIES[1] - configurations = { - "instrumentation_config": { - libr_name: { - "test_key": "test_value", - }, - libr_name2: { - "test_key2": "test_value2", - }, - }, - "exclude_instrumentations": libr_name, - } - ep_mock = Mock() - ep2_mock = Mock() - iter_mock.return_value = (ep_mock, ep2_mock) - instrumentor_mock = Mock() - instr_class_mock = Mock() - instr_class_mock.return_value = instrumentor_mock - ep_mock.name = libr_name - ep2_mock.name = libr_name2 - ep2_mock.load.return_value = instr_class_mock - dep_mock.return_value = None - _setup_instrumentations(configurations) - iter_mock.assert_called_with("opentelemetry_instrumentor") - dep_mock.assert_called_with(ep2_mock.dist) - ep2_mock.load.assert_called_once() - instrumentor_mock.instrument.assert_called_once_with( - **{"test_key2": "test_value2", "skip_dep_check": True} - ) diff --git a/azure-monitor-opentelemetry/tests/configuration/test_util.py b/azure-monitor-opentelemetry/tests/configuration/test_util.py index 34496868..8fd9d271 100644 --- a/azure-monitor-opentelemetry/tests/configuration/test_util.py +++ b/azure-monitor-opentelemetry/tests/configuration/test_util.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from logging import NOTSET from unittest import TestCase from unittest.mock import patch @@ -32,76 +31,40 @@ class TestUtil(TestCase): def test_get_configurations(self): configurations = _get_configurations( connection_string="test_cs", - exclude_instrumentations="test_exclude_instrumentations", - disable_logging="test_disable_logging", - disable_metrics="test_disable_metrics", - disable_tracing="test_disable_tracing", - logging_level="test_logging_level", - logger_name="test_logger_name", - resource="test_resource", - sampling_ratio="test_sample_ratio", - tracing_export_interval_ms=10000, - logging_export_interval_ms=10000, - metric_readers=("test_readers"), - views=("test_view"), - instrumentation_config="test_instrumentation_config", credential="test_credential", ) self.assertEqual(configurations["connection_string"], "test_cs") - self.assertEqual( - configurations["exclude_instrumentations"], - "test_exclude_instrumentations", - ) - self.assertEqual( - configurations["disable_logging"], "test_disable_logging" - ) - self.assertEqual( - configurations["disable_metrics"], "test_disable_metrics" - ) - self.assertEqual( - configurations["disable_tracing"], "test_disable_tracing" - ) - self.assertEqual(configurations["logging_level"], "test_logging_level") - self.assertEqual(configurations["logger_name"], "test_logger_name") - self.assertEqual(configurations["resource"], "test_resource") - self.assertEqual(configurations["sampling_ratio"], "test_sample_ratio") - self.assertEqual(configurations["tracing_export_interval_ms"], 10000) - self.assertEqual(configurations["logging_export_interval_ms"], 10000) - self.assertEqual(configurations["metric_readers"], ("test_readers")) - self.assertEqual(configurations["views"], ("test_view")) - self.assertEqual( - configurations["instrumentation_config"], - ("test_instrumentation_config"), - ) + self.assertEqual(configurations["disable_logging"], False) + self.assertEqual(configurations["disable_metrics"], False) + self.assertEqual(configurations["disable_tracing"], False) + self.assertEqual(configurations["sampling_ratio"], 1.0) + self.assertEqual(configurations["logging_export_interval_ms"], 5000) self.assertEqual(configurations["credential"], ("test_credential")) + self.assertTrue("storage_directory" not in configurations) @patch.dict("os.environ", {}, clear=True) def test_get_configurations_defaults(self): configurations = _get_configurations() self.assertTrue("connection_string" not in configurations) - self.assertEqual(configurations["exclude_instrumentations"], []) self.assertEqual(configurations["disable_logging"], False) self.assertEqual(configurations["disable_metrics"], False) self.assertEqual(configurations["disable_tracing"], False) - self.assertEqual(configurations["logging_level"], NOTSET) - self.assertEqual(configurations["logger_name"], "") - self.assertTrue("resource" not in configurations) self.assertEqual(configurations["sampling_ratio"], 1.0) - self.assertEqual(configurations["tracing_export_interval_ms"], None) self.assertEqual(configurations["logging_export_interval_ms"], 5000) - self.assertEqual(configurations["metric_readers"], []) - self.assertEqual(configurations["views"], ()) - self.assertEqual(configurations["instrumentation_config"], {}) + self.assertTrue("credential" not in configurations) + self.assertTrue("storage_directory" not in configurations) - def test_get_configurations_validation(self): - self.assertRaises( - ValueError, _get_configurations, logging_export_interval_ms=-0.5 - ) - self.assertRaises( - ValueError, _get_configurations, logging_export_interval_ms=-1 - ) + @patch.dict( + "os.environ", + { + LOGGING_EXPORT_INTERVAL_MS_ENV_VAR: "-1", + }, + clear=True, + ) + def test_get_configurations_logging_export_validation(self): + self.assertRaises(ValueError, _get_configurations) @patch.dict( "os.environ", @@ -118,19 +81,11 @@ def test_get_configurations_env_vars(self): configurations = _get_configurations() self.assertTrue("connection_string" not in configurations) - self.assertEqual(configurations["exclude_instrumentations"], []) self.assertEqual(configurations["disable_logging"], True) self.assertEqual(configurations["disable_metrics"], True) self.assertEqual(configurations["disable_tracing"], True) - self.assertEqual(configurations["logging_level"], NOTSET) - self.assertEqual(configurations["logger_name"], "") - self.assertTrue("resource" not in configurations) self.assertEqual(configurations["sampling_ratio"], 0.5) - self.assertEqual(configurations["tracing_export_interval_ms"], None) - self.assertEqual(configurations["logging_export_interval_ms"], 5000) - self.assertEqual(configurations["metric_readers"], []) - self.assertEqual(configurations["views"], ()) - self.assertEqual(configurations["instrumentation_config"], {}) + self.assertEqual(configurations["logging_export_interval_ms"], 10000) @patch.dict( "os.environ", @@ -147,16 +102,8 @@ def test_get_configurations_env_vars_validation(self): configurations = _get_configurations() self.assertTrue("connection_string" not in configurations) - self.assertEqual(configurations["exclude_instrumentations"], []) self.assertEqual(configurations["disable_logging"], False) self.assertEqual(configurations["disable_metrics"], False) self.assertEqual(configurations["disable_tracing"], False) - self.assertEqual(configurations["logging_level"], NOTSET) - self.assertEqual(configurations["logger_name"], "") - self.assertTrue("resource" not in configurations) self.assertEqual(configurations["sampling_ratio"], 1.0) - self.assertEqual(configurations["tracing_export_interval_ms"], None) self.assertEqual(configurations["logging_export_interval_ms"], 5000) - self.assertEqual(configurations["metric_readers"], []) - self.assertEqual(configurations["views"], ()) - self.assertEqual(configurations["instrumentation_config"], {})