1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
import os
import platform
import shutil
import unittest
from unittest import mock
from functools import partial
# pylint: disable=import-error
from opentelemetry.semconv.attributes.exception_attributes import (
EXCEPTION_MESSAGE,
EXCEPTION_STACKTRACE,
EXCEPTION_TYPE,
)
from opentelemetry.sdk import _logs
from opentelemetry.sdk.util.instrumentation import InstrumentationScope
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk._logs.export import LogExportResult
from opentelemetry._logs.severity import SeverityNumber
from azure.monitor.opentelemetry.exporter.export._base import ExportResult
from azure.monitor.opentelemetry.exporter.export.logs._exporter import (
AzureMonitorLogExporter,
_get_log_export_result,
_get_severity_level,
)
from azure.monitor.opentelemetry.exporter._constants import (
_APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE,
_MICROSOFT_CUSTOM_EVENT_NAME,
)
from azure.monitor.opentelemetry.exporter._generated.models import ContextTagKeys
from azure.monitor.opentelemetry.exporter._utils import (
azure_monitor_context,
ns_to_iso_str,
)
def throw(exc_type, *args, **kwargs):
def func(*_args, **_kwargs):
raise exc_type(*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["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"},
),
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"}),
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={
"event_key": "event_attribute",
_APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE: True,
},
),
InstrumentationScope("test_name"),
)
cls._log_data_event_complex_body = _logs.LogData(
_logs.LogRecord(
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={
"event_key": "event_attribute",
_APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE: True,
},
),
InstrumentationScope("test_name"),
)
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=NotSerializeableClass(),
resource=Resource.create(attributes={"asd": "test_resource"}),
attributes={
"event_key": "event_attribute",
_APPLICATION_INSIGHTS_EVENT_MARKER_ATTRIBUTE: True,
},
),
InstrumentationScope("test_name"),
)
cls._log_data_custom_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={
"event_key": "event_attribute",
_MICROSOFT_CUSTOM_EVENT_NAME: "event_name",
"client.address": "192.168.1.1",
},
),
InstrumentationScope("test_name"),
)
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"}),
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 <module>\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"}),
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 <module>\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: ""},
),
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: ""},
),
InstrumentationScope("test_name"),
)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls._exporter.storage._path, True)
def test_constructor(self):
"""Test the constructor."""
exporter = AzureMonitorLogExporter(
connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab",
)
self.assertEqual(
exporter._instrumentation_key,
"4321abcd-5678-4efa-8abc-1234567890ab",
)
self.assertIsNotNone(exporter.storage)
def test_from_connection_string(self):
exporter = AzureMonitorLogExporter.from_connection_string(
"InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab"
)
self.assertTrue(isinstance(exporter, AzureMonitorLogExporter))
self.assertEqual(
exporter._instrumentation_key,
"4321abcd-5678-4efa-8abc-1234567890ab",
)
def test_export_empty(self):
exporter = self._exporter
result = exporter.export([])
self.assertEqual(result, LogExportResult.SUCCESS)
def test_export_failure(self):
exporter = self._exporter
with mock.patch(
"azure.monitor.opentelemetry.exporter.AzureMonitorLogExporter._transmit"
) as transmit: # noqa: E501
transmit.return_value = ExportResult.FAILED_RETRYABLE
storage_mock = mock.Mock()
exporter.storage.put = storage_mock
result = exporter.export([self._log_data])
self.assertEqual(result, LogExportResult.FAILURE)
self.assertEqual(storage_mock.call_count, 1)
def test_export_success(self):
exporter = self._exporter
with mock.patch(
"azure.monitor.opentelemetry.exporter.AzureMonitorLogExporter._transmit"
) as transmit: # noqa: E501
transmit.return_value = ExportResult.SUCCESS
storage_mock = mock.Mock()
exporter._transmit_from_storage = storage_mock
result = exporter.export([self._log_data])
self.assertEqual(result, LogExportResult.SUCCESS)
self.assertEqual(storage_mock.call_count, 1)
@mock.patch("azure.monitor.opentelemetry.exporter.export.logs._exporter._logger")
def test_export_exception(self, logger_mock):
exporter = self._exporter
with mock.patch(
"azure.monitor.opentelemetry.exporter.AzureMonitorLogExporter._transmit",
throw(Exception),
): # noqa: E501
result = exporter.export([self._log_data])
self.assertEqual(result, LogExportResult.FAILURE)
self.assertEqual(logger_mock.exception.called, True)
def test_export_not_retryable(self):
exporter = self._exporter
with mock.patch(
"azure.monitor.opentelemetry.exporter.AzureMonitorLogExporter._transmit"
) as transmit: # noqa: E501
transmit.return_value = ExportResult.FAILED_NOT_RETRYABLE
result = exporter.export([self._log_data])
self.assertEqual(result, LogExportResult.FAILURE)
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",
}
)
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.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_CLOUD_ROLE), "testServiceNamespace.testServiceName")
self.assertEqual(envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), "testServiceInstanceId")
self.assertEqual(envelope.tags.get(ContextTagKeys.AI_INTERNAL_NODE_NAME), "testServiceInstanceId")
trace_id = self._log_data.log_record.trace_id
self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_ID), "{:032x}".format(trace_id))
span_id = self._log_data.log_record.span_id
self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_PARENT_ID), "{:016x}".format(span_id))
self._log_data.log_record.resource = old_resource
def test_log_to_envelope_partA_default(self):
exporter = self._exporter
old_resource = self._log_data.log_record.resource
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._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.time, ns_to_iso_str(record.timestamp))
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")
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, "")
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, "")
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.time, ns_to_iso_str(record.timestamp))
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 <module>\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.time, ns_to_iso_str(record.timestamp))
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 <module>\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.time, ns_to_iso_str(record.timestamp))
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, "Exception")
self.assertEqual(envelope.data.base_data.exceptions[0].message, "Exception")
self.assertTrue(envelope.data.base_data.exceptions[0].has_full_stack)
self.assertEqual(envelope.data.base_data.exceptions[0].stack, "")
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.time, ns_to_iso_str(record.timestamp))
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, "Exception")
self.assertEqual(envelope.data.base_data.exceptions[0].message, "test exception")
self.assertTrue(envelope.data.base_data.exceptions[0].has_full_stack)
self.assertEqual(envelope.data.base_data.exceptions[0].stack, "")
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.time, ns_to_iso_str(record.timestamp))
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_custom_event(self):
exporter = self._exporter
envelope = exporter._log_to_envelope(self._log_data_custom_event)
record = self._log_data_custom_event.log_record
self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Event")
self.assertEqual(envelope.tags["ai.location.ip"], "192.168.1.1")
self.assertEqual(envelope.time, ns_to_iso_str(record.timestamp))
self.assertEqual(envelope.data.base_type, "EventData")
self.assertEqual(envelope.data.base_data.name, "event_name")
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
self._log_data.log_record.timestamp = None
self._log_data.log_record.observed_timestamp = 1646865018558419457
envelope = exporter._log_to_envelope(self._log_data)
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(
connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab",
disable_offline_storage=True,
)
self.assertEqual(
exporter._instrumentation_key,
"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(
"azure.monitor.opentelemetry.exporter.AzureMonitorLogExporter._transmit"
) as transmit: # noqa: E501
transmit.return_value = ExportResult.FAILED_NOT_RETRYABLE
transmit_from_storage_mock = mock.Mock()
exporter._handle_transmit_from_storage = transmit_from_storage_mock
result = exporter.export([self._log_data])
self.assertEqual(result, LogExportResult.FAILURE)
self.assertEqual(exporter.storage, None)
self.assertEqual(transmit_from_storage_mock.call_count, 1)
def test_export_success(self):
exporter = self._exporter
with mock.patch(
"azure.monitor.opentelemetry.exporter.AzureMonitorLogExporter._transmit"
) as transmit: # noqa: E501
transmit.return_value = ExportResult.SUCCESS
storage_mock = mock.Mock()
exporter._transmit_from_storage = storage_mock
result = exporter.export([self._log_data])
self.assertEqual(result, LogExportResult.SUCCESS)
self.assertEqual(storage_mock.call_count, 0)
class TestAzureLogExporterUtils(unittest.TestCase):
def test_get_log_export_result(self):
self.assertEqual(
_get_log_export_result(ExportResult.SUCCESS),
LogExportResult.SUCCESS,
)
self.assertEqual(
_get_log_export_result(ExportResult.FAILED_NOT_RETRYABLE),
LogExportResult.FAILURE,
)
self.assertEqual(
_get_log_export_result(ExportResult.FAILED_RETRYABLE),
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):
self.assertEqual(level, 0)
elif num in range(9, 13):
self.assertEqual(level, 1)
elif num in range(13, 17):
self.assertEqual(level, 2)
elif num in range(17, 21):
self.assertEqual(level, 3)
else:
self.assertEqual(level, 4)
|