3636from opentelemetry .semconv .trace import SpanAttributes
3737
3838from azure .monitor .opentelemetry .exporter ._constants import (
39+ _APPLICATIONINSIGHTS_METRICS_TO_LOGANALYTICS_ENABLED ,
3940 _APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN ,
4041 _AUTOCOLLECTED_INSTRUMENT_NAMES ,
4142 _METRIC_ENVELOPE_NAME ,
@@ -80,6 +81,7 @@ def __init__(self, **kwargs: Any) -> None:
8081 preferred_temporality = APPLICATION_INSIGHTS_METRIC_TEMPORALITIES , # type: ignore
8182 preferred_aggregation = kwargs .get ("preferred_aggregation" ), # type: ignore
8283 )
84+ self ._metrics_to_log_analytics = self ._determine_metrics_to_log_analytics ()
8385
8486 # pylint: disable=R1702
8587 def export (
@@ -152,6 +154,9 @@ def _point_to_envelope(
152154 resource : Optional [Resource ] = None ,
153155 scope : Optional [InstrumentationScope ] = None ,
154156 ) -> Optional [TelemetryItem ]:
157+ # When Metrics to Log Analytics is disabled, only send Standard metrics and _OTELRESOURCE_
158+ if not self ._metrics_to_log_analytics and name not in _AUTOCOLLECTED_INSTRUMENT_NAMES :
159+ return None
155160 envelope = _convert_point_to_envelope (point , name , resource , scope )
156161 if name in _AUTOCOLLECTED_INSTRUMENT_NAMES :
157162 envelope = _handle_std_metric_envelope (envelope , name , point .attributes ) # type: ignore
@@ -169,6 +174,22 @@ def _point_to_envelope(
169174
170175 return envelope
171176
177+ # pylint: disable=protected-access
178+ def _determine_metrics_to_log_analytics (self ) -> bool :
179+ """
180+ Determines whether metrics should be sent to Log Analytics.
181+
182+ :return: False if metrics should not be sent to Log Analytics, True otherwise.
183+ :rtype: bool
184+ """
185+ # Disabling metrics to Log Analytics via env var is currently only specified for AKS Attach scenarios.
186+ if not _utils ._is_on_aks () or not _utils ._is_attach_enabled () or self ._is_stats_exporter ():
187+ return True
188+ env_var = os .environ .get (_APPLICATIONINSIGHTS_METRICS_TO_LOGANALYTICS_ENABLED )
189+ if not env_var :
190+ return True
191+ return env_var .lower ().strip () != "false"
192+
172193 # pylint: disable=docstring-keyword-should-match-keyword-only
173194 @classmethod
174195 def from_connection_string (cls , conn_str : str , ** kwargs : Any ) -> "AzureMonitorMetricExporter" :
0 commit comments