Skip to content

Commit feed2c9

Browse files
authored
Add message ids for applens (#32195)
* working * removed comments * Tests pass * tests pass * Add exc tests * lint * remove unused field * feedback
1 parent 1b66fcf commit feed2c9

9 files changed

Lines changed: 151 additions & 168 deletions

File tree

sdk/monitor/azure-monitor-opentelemetry/CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
## 1.0.1 (Unreleased)
44

5+
- Add message ids for AppLens
6+
([#32195](https://github.com/Azure/azure-sdk-for-python/pull/32195))
7+
58
### Features Added
69

710
- Add ability to specify which logger to export telemetry for via `logger_name` configuration

sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_autoinstrumentation/configurator.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
# --------------------------------------------------------------------------
66

77

8-
import logging
98
from warnings import warn
109

1110
from opentelemetry.sdk._configuration import _OTelSDKConfigurator
@@ -16,25 +15,28 @@
1615
)
1716
from azure.monitor.opentelemetry._diagnostics.diagnostic_logging import (
1817
AzureDiagnosticLogging,
18+
_ATTACH_FAILURE_CONFIGURATOR,
19+
_ATTACH_SUCCESS_CONFIGURATOR,
20+
)
21+
from azure.monitor.opentelemetry._diagnostics.status_logger import (
22+
AzureStatusLogger,
1923
)
20-
21-
_logger = logging.getLogger(__name__)
2224

2325

2426
class AzureMonitorConfigurator(_OTelSDKConfigurator):
2527
def _configure(self, **kwargs):
2628
if not _is_attach_enabled():
2729
warn(_PREVIEW_ENTRY_POINT_WARNING)
2830
try:
29-
AzureDiagnosticLogging.enable(_logger)
3031
super()._configure(**kwargs)
31-
except ValueError as e:
32-
_logger.error(
33-
"Azure Monitor Configurator failed during configuration due to a ValueError: %s", e
32+
AzureStatusLogger.log_status(True)
33+
AzureDiagnosticLogging.info(
34+
"Azure Monitor Configurator configured successfully.",
35+
_ATTACH_SUCCESS_CONFIGURATOR
3436
)
35-
raise e
3637
except Exception as e:
37-
_logger.error(
38-
"Azure Monitor Configurator failed during configuration: %s", e
38+
AzureDiagnosticLogging.error(
39+
"Azure Monitor Configurator failed during configuration: %s" % str(e),
40+
_ATTACH_FAILURE_CONFIGURATOR,
3941
)
4042
raise e

sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_autoinstrumentation/distro.py

Lines changed: 26 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
# Licensed under the MIT License. See License in the project root for
44
# license information.
55
# --------------------------------------------------------------------------
6-
import logging
76
from os import environ
87
from warnings import warn
98

@@ -27,55 +26,45 @@
2726
)
2827
from azure.monitor.opentelemetry._diagnostics.diagnostic_logging import (
2928
AzureDiagnosticLogging,
29+
_ATTACH_FAILURE_DISTRO,
30+
_ATTACH_SUCCESS_DISTRO,
3031
)
3132
from azure.monitor.opentelemetry._diagnostics.status_logger import (
3233
AzureStatusLogger,
3334
)
3435

35-
_CONFIG_FAILED_MSG = "Azure Monitor OpenTelemetry Distro failed during configuration: %s"
36-
37-
_logger = logging.getLogger(__name__)
38-
_opentelemetry_logger = logging.getLogger("opentelemetry")
39-
# TODO: Enabled when duplicate logging issue is solved
40-
# _exporter_logger = logging.getLogger("azure.monitor.opentelemetry.exporter")
41-
4236

4337
class AzureMonitorDistro(BaseDistro):
4438
def _configure(self, **kwargs) -> None:
4539
if not _is_attach_enabled():
4640
warn(_PREVIEW_ENTRY_POINT_WARNING)
4741
try:
4842
_configure_auto_instrumentation()
49-
except Exception as ex:
50-
_logger.exception(
51-
("Error occurred auto-instrumenting AzureMonitorDistro")
43+
AzureStatusLogger.log_status(True)
44+
AzureDiagnosticLogging.info(
45+
"Azure Monitor OpenTelemetry Distro configured successfully.",
46+
_ATTACH_SUCCESS_DISTRO
47+
)
48+
except Exception as e:
49+
AzureStatusLogger.log_status(False, reason=str(e))
50+
AzureDiagnosticLogging.error(
51+
"Azure Monitor OpenTelemetry Distro failed during configuration: %s" % str(e),
52+
_ATTACH_FAILURE_DISTRO,
5253
)
53-
raise ex
54+
raise e
5455

5556

5657
def _configure_auto_instrumentation() -> None:
57-
try:
58-
AzureStatusLogger.log_status(False, "Distro being configured.")
59-
AzureDiagnosticLogging.enable(_logger)
60-
AzureDiagnosticLogging.enable(_opentelemetry_logger)
61-
environ.setdefault(
62-
OTEL_METRICS_EXPORTER, "azure_monitor_opentelemetry_exporter"
63-
)
64-
environ.setdefault(
65-
OTEL_TRACES_EXPORTER, "azure_monitor_opentelemetry_exporter"
66-
)
67-
environ.setdefault(
68-
OTEL_LOGS_EXPORTER, "azure_monitor_opentelemetry_exporter"
69-
)
70-
environ.setdefault(
71-
_OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED, "true"
72-
)
73-
settings.tracing_implementation = OpenTelemetrySpan
74-
AzureStatusLogger.log_status(True)
75-
_logger.info(
76-
"Azure Monitor OpenTelemetry Distro configured successfully."
77-
)
78-
except Exception as exc:
79-
AzureStatusLogger.log_status(False, reason=exc)
80-
_logger.error(_CONFIG_FAILED_MSG, exc)
81-
raise exc
58+
environ.setdefault(
59+
OTEL_METRICS_EXPORTER, "azure_monitor_opentelemetry_exporter"
60+
)
61+
environ.setdefault(
62+
OTEL_TRACES_EXPORTER, "azure_monitor_opentelemetry_exporter"
63+
)
64+
environ.setdefault(
65+
OTEL_LOGS_EXPORTER, "azure_monitor_opentelemetry_exporter"
66+
)
67+
environ.setdefault(
68+
_OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED, "true"
69+
)
70+
settings.tracing_implementation = OpenTelemetrySpan

sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_constants.py

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,6 @@
3333
_IS_ON_APP_SERVICE = "WEBSITE_SITE_NAME" in environ
3434
# TODO: Add environment variable to enabled diagnostics off of App Service
3535
_IS_DIAGNOSTICS_ENABLED = _IS_ON_APP_SERVICE
36-
# TODO: Enabled when duplicate logging issue is solved
37-
# _EXPORTER_DIAGNOSTICS_ENABLED_ENV_VAR = (
38-
# "AZURE_MONITOR_OPENTELEMETRY_DISTRO_ENABLE_EXPORTER_DIAGNOSTICS"
39-
# )
4036
_CUSTOMER_IKEY_ENV_VAR = None
4137
_PREVIEW_ENTRY_POINT_WARNING = "Autoinstrumentation for the Azure Monitor OpenTelemetry Distro is in preview."
4238
logger = logging.getLogger(__name__)
@@ -75,19 +71,9 @@ def _env_var_or_default(var_name, default_val=""):
7571
return default_val
7672

7773

78-
# TODO: Enabled when duplicate logging issue is solved
79-
# def _is_exporter_diagnostics_enabled():
80-
# return (
81-
# _EXPORTER_DIAGNOSTICS_ENABLED_ENV_VAR in environ
82-
# and environ[_EXPORTER_DIAGNOSTICS_ENABLED_ENV_VAR] == "True"
83-
# )
84-
85-
8674
_EXTENSION_VERSION = _env_var_or_default(
8775
"ApplicationInsightsAgent_EXTENSION_VERSION", "disabled"
8876
)
89-
# TODO: Enabled when duplicate logging issue is solved
90-
# _EXPORTER_DIAGNOSTICS_ENABLED = _is_exporter_diagnostics_enabled()
9177

9278

9379
def _is_attach_enabled():

sdk/monitor/azure-monitor-opentelemetry/azure/monitor/opentelemetry/_diagnostics/diagnostic_logging.py

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,18 @@
2525
_SUBSCRIPTION_ID_ENV_VAR.split("+")[0] if _SUBSCRIPTION_ID_ENV_VAR else None
2626
)
2727
_logger = logging.getLogger(__name__)
28+
_logger.propagate = False
29+
_logger.setLevel(logging.INFO)
2830
_DIAGNOSTIC_LOG_PATH = _get_log_path()
31+
_ATTACH_SUCCESS_DISTRO = "4200"
32+
_ATTACH_SUCCESS_CONFIGURATOR = "4201"
33+
_ATTACH_FAILURE_DISTRO = "4400"
34+
_ATTACH_FAILURE_CONFIGURATOR = "4401"
2935

3036

3137
class AzureDiagnosticLogging:
3238
_initialized = False
3339
_lock = threading.Lock()
34-
_f_handler = None
3540

3641
@classmethod
3742
def _initialize(cls):
@@ -51,29 +56,36 @@ def _initialize(cls):
5156
+ f'"extensionVersion":"{_EXTENSION_VERSION}", '
5257
+ f'"sdkVersion":"{VERSION}", '
5358
+ f'"subscriptionId":"{_SUBSCRIPTION_ID}", '
59+
+ '"msgId":"%(msgId)s", '
5460
+ '"language":"python"'
5561
+ "}"
5662
+ "}"
5763
)
5864
if not exists(_DIAGNOSTIC_LOG_PATH):
5965
makedirs(_DIAGNOSTIC_LOG_PATH)
60-
AzureDiagnosticLogging._f_handler = logging.FileHandler(
66+
f_handler = logging.FileHandler(
6167
join(
6268
_DIAGNOSTIC_LOG_PATH, _DIAGNOSTIC_LOGGER_FILE_NAME
6369
)
6470
)
6571
formatter = logging.Formatter(
6672
fmt=log_format, datefmt="%Y-%m-%dT%H:%M:%S"
6773
)
68-
AzureDiagnosticLogging._f_handler.setFormatter(formatter)
74+
f_handler.setFormatter(formatter)
75+
_logger.addHandler(f_handler)
6976
AzureDiagnosticLogging._initialized = True
70-
_logger.info("Initialized Azure Diagnostic Logger.")
7177

7278
@classmethod
73-
def enable(cls, logger: logging.Logger):
79+
def info(cls, message: str, message_id: int):
7480
AzureDiagnosticLogging._initialize()
75-
if AzureDiagnosticLogging._initialized and AzureDiagnosticLogging._f_handler:
76-
logger.addHandler(AzureDiagnosticLogging._f_handler)
77-
_logger.info(
78-
"Added Azure diagnostics logging to %s.", logger.name
79-
)
81+
_logger.info(message, extra={'msgId': message_id})
82+
83+
@classmethod
84+
def warning(cls, message: str, message_id: int):
85+
AzureDiagnosticLogging._initialize()
86+
_logger.warning(message, extra={'msgId': message_id})
87+
88+
@classmethod
89+
def error(cls, message: str, message_id: int):
90+
AzureDiagnosticLogging._initialize()
91+
_logger.error(message, extra={'msgId': message_id})

sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_configurator.py

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,51 @@
66
from azure.monitor.opentelemetry._autoinstrumentation.configurator import (
77
AzureMonitorConfigurator,
88
)
9+
from azure.monitor.opentelemetry._diagnostics.diagnostic_logging import (
10+
_ATTACH_FAILURE_CONFIGURATOR,
11+
_ATTACH_SUCCESS_CONFIGURATOR
12+
)
913

1014

1115
class TestConfigurator(TestCase):
1216
@patch("azure.monitor.opentelemetry._autoinstrumentation.configurator._is_attach_enabled", return_value=True)
1317
@patch(
14-
"azure.monitor.opentelemetry._autoinstrumentation.configurator.AzureDiagnosticLogging.enable"
18+
"azure.monitor.opentelemetry._autoinstrumentation.configurator.AzureDiagnosticLogging"
1519
)
1620
def test_configure(self, mock_diagnostics, attach_mock):
1721
configurator = AzureMonitorConfigurator()
1822
with warnings.catch_warnings():
1923
warnings.simplefilter("error")
2024
configurator._configure()
21-
mock_diagnostics.assert_called_once()
25+
mock_diagnostics.info.assert_called_once_with(
26+
"Azure Monitor Configurator configured successfully.",
27+
_ATTACH_SUCCESS_CONFIGURATOR
28+
)
2229

2330
@patch("azure.monitor.opentelemetry._autoinstrumentation.configurator._is_attach_enabled", return_value=False)
2431
@patch(
25-
"azure.monitor.opentelemetry._autoinstrumentation.configurator.AzureDiagnosticLogging.enable"
32+
"azure.monitor.opentelemetry._autoinstrumentation.configurator.AzureDiagnosticLogging"
2633
)
2734
def test_configure_preview(self, mock_diagnostics, attach_mock):
2835
configurator = AzureMonitorConfigurator()
2936
with self.assertWarns(Warning):
3037
configurator._configure()
31-
mock_diagnostics.assert_called_once()
38+
mock_diagnostics.info.assert_called_once_with(
39+
"Azure Monitor Configurator configured successfully.",
40+
_ATTACH_SUCCESS_CONFIGURATOR
41+
)
42+
43+
@patch("azure.monitor.opentelemetry._autoinstrumentation.configurator.super")
44+
@patch("azure.monitor.opentelemetry._autoinstrumentation.configurator._is_attach_enabled", return_value=True)
45+
@patch(
46+
"azure.monitor.opentelemetry._autoinstrumentation.configurator.AzureDiagnosticLogging"
47+
)
48+
def test_configure_exc(self, mock_diagnostics, attach_mock, super_mock):
49+
configurator = AzureMonitorConfigurator()
50+
super_mock()._configure.side_effect = Exception("Test Exception")
51+
with self.assertRaises(Exception):
52+
configurator._configure()
53+
mock_diagnostics.error.assert_called_once_with(
54+
"Azure Monitor Configurator failed during configuration: Test Exception",
55+
_ATTACH_FAILURE_CONFIGURATOR
56+
)

sdk/monitor/azure-monitor-opentelemetry/tests/autoinstrumentation/test_distro.py

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,34 +6,60 @@
66
from azure.monitor.opentelemetry._autoinstrumentation.distro import (
77
AzureMonitorDistro,
88
)
9+
from azure.monitor.opentelemetry._diagnostics.diagnostic_logging import (
10+
_ATTACH_FAILURE_DISTRO,
11+
_ATTACH_SUCCESS_DISTRO
12+
)
913

1014

1115
class TestDistro(TestCase):
1216
@patch("azure.monitor.opentelemetry._autoinstrumentation.distro._is_attach_enabled", return_value=True)
1317
@patch("azure.monitor.opentelemetry._autoinstrumentation.distro.settings")
1418
@patch(
15-
"azure.monitor.opentelemetry._autoinstrumentation.distro.AzureDiagnosticLogging.enable"
19+
"azure.monitor.opentelemetry._autoinstrumentation.distro.AzureDiagnosticLogging"
1620
)
1721
def test_configure(self, mock_diagnostics, azure_core_mock, attach_mock):
1822
distro = AzureMonitorDistro()
1923
with warnings.catch_warnings():
2024
warnings.simplefilter("error")
2125
distro.configure()
22-
self.assertEqual(mock_diagnostics.call_count, 2)
26+
mock_diagnostics.info.assert_called_once_with(
27+
"Azure Monitor OpenTelemetry Distro configured successfully.",
28+
_ATTACH_SUCCESS_DISTRO
29+
)
2330
self.assertEqual(
2431
azure_core_mock.tracing_implementation, OpenTelemetrySpan
2532
)
2633

2734
@patch("azure.monitor.opentelemetry._autoinstrumentation.distro._is_attach_enabled", return_value=False)
2835
@patch("azure.monitor.opentelemetry._autoinstrumentation.distro.settings")
2936
@patch(
30-
"azure.monitor.opentelemetry._autoinstrumentation.distro.AzureDiagnosticLogging.enable"
37+
"azure.monitor.opentelemetry._autoinstrumentation.distro.AzureDiagnosticLogging"
3138
)
3239
def test_configure_preview(self, mock_diagnostics, azure_core_mock, attach_mock):
3340
distro = AzureMonitorDistro()
3441
with self.assertWarns(Warning):
3542
distro.configure()
36-
self.assertEqual(mock_diagnostics.call_count, 2)
43+
mock_diagnostics.info.assert_called_once_with(
44+
"Azure Monitor OpenTelemetry Distro configured successfully.",
45+
_ATTACH_SUCCESS_DISTRO
46+
)
3747
self.assertEqual(
3848
azure_core_mock.tracing_implementation, OpenTelemetrySpan
3949
)
50+
51+
@patch("azure.monitor.opentelemetry._autoinstrumentation.distro._configure_auto_instrumentation")
52+
@patch("azure.monitor.opentelemetry._autoinstrumentation.distro._is_attach_enabled", return_value=True)
53+
@patch("azure.monitor.opentelemetry._autoinstrumentation.distro.settings")
54+
@patch(
55+
"azure.monitor.opentelemetry._autoinstrumentation.distro.AzureDiagnosticLogging"
56+
)
57+
def test_configure_exc(self, mock_diagnostics, azure_core_mock, attach_mock, configure_mock):
58+
distro = AzureMonitorDistro()
59+
configure_mock.side_effect = Exception("Test Exception")
60+
with self.assertRaises(Exception):
61+
distro.configure()
62+
mock_diagnostics.error.assert_called_once_with(
63+
"Azure Monitor OpenTelemetry Distro failed during configuration: Test Exception",
64+
_ATTACH_FAILURE_DISTRO
65+
)

0 commit comments

Comments
 (0)