warpzone-sdk 15.0.0.dev10__py3-none-any.whl → 15.0.0.dev11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,43 @@
1
- import inspect
1
+ import asyncio
2
+ import logging
2
3
  from contextlib import contextmanager
3
4
  from typing import Callable
4
5
 
5
6
  import azure.functions as func
6
7
 
7
8
  from warpzone.function.types import SingleArgumentCallable
8
- from warpzone.monitor import traces
9
-
10
- # Configure tracing at import time (once per worker process)
11
- traces.configure_tracing()
9
+ from warpzone.monitor import logs, traces
12
10
 
13
11
  SUBJECT_IDENTIFIER = "<Subject>"
14
12
 
13
+ tracer = traces.get_tracer(__name__)
14
+ logger = logs.get_logger(__name__)
15
15
 
16
- @contextmanager
17
- def run_in_trace_context(context: func.Context):
18
- """Set up trace context and ensure log correlation for this function invocation.
19
16
 
20
- This sets:
21
- 1. OpenTelemetry trace context (for distributed tracing via Service Bus)
22
- 2. Azure Functions invocation_id in thread-local storage (for log correlation)
17
+ def configure_monitoring():
23
18
  """
24
- # Ensure Azure Functions' log correlation uses this invocation's ID
25
- # This prevents log leakage when multiple functions run concurrently
26
- context.thread_local_storage.invocation_id = context.invocation_id
19
+ Configure logging and tracing on Azure Function to
20
+ - export telemetry to App Insights
21
+ - suppress spamming logs
22
+ """
23
+ # disable logging for HTTP calls to avoid log spamming
24
+ logging.getLogger("azure.core.pipeline.policies.http_logging_policy").setLevel(
25
+ logging.WARNING
26
+ )
27
+
28
+ # disable logging for Service Bus underlying uAMQP library to avoid log spamming
29
+ logging.getLogger("uamqp").setLevel(logging.WARNING)
30
+
31
+ # configure tracer provider
32
+ traces.configure_tracing()
33
+
34
+ # configure logger provider
35
+ logs.configure_logging()
36
+
37
+
38
+ @contextmanager
39
+ def run_in_trace_context(context: func.Context):
40
+ configure_monitoring()
27
41
 
28
42
  trace_context = context.trace_context
29
43
  with traces.set_trace_context(
@@ -61,7 +75,7 @@ def monitor(main: SingleArgumentCallable) -> Callable:
61
75
  result = main(arg)
62
76
  return result
63
77
 
64
- if inspect.iscoroutinefunction(main):
78
+ if asyncio.iscoroutinefunction(main):
65
79
  return wrapper_async
66
80
  else:
67
81
  return wrapper
@@ -1,2 +1,2 @@
1
1
  from .logs import get_logger
2
- from .traces import get_current_diagnostic_id, get_tracer
2
+ from .traces import get_current_diagnostic_id, get_tracer, servicebus_send_span
warpzone/monitor/logs.py CHANGED
@@ -1,33 +1,78 @@
1
+ # NOTE: OpenTelemetry logging to Azure is still in EXPERIMENTAL mode!
1
2
  import logging
3
+ import os
4
+ from logging import StreamHandler
2
5
 
3
- # Suppress verbose logging from Azure SDK
4
- logging.getLogger("azure.core.pipeline.policies.http_logging_policy").setLevel(
5
- logging.WARNING
6
- )
7
- logging.getLogger("azure.data.tables").setLevel(logging.WARNING)
8
- logging.getLogger("azure.storage.blob").setLevel(logging.WARNING)
9
- logging.getLogger("azure.servicebus").setLevel(logging.WARNING)
10
- logging.getLogger("uamqp").setLevel(logging.WARNING)
11
- logging.getLogger("azure.identity").setLevel(logging.WARNING)
12
- # Suppress Azure Functions host/worker logging (e.g., trigger details)
13
- logging.getLogger("azure_functions_worker").setLevel(logging.WARNING)
14
- logging.getLogger("azure.functions").setLevel(logging.WARNING)
15
- # Suppress Azure Monitor exporter logging (e.g., transmission success messages)
16
- logging.getLogger("azure.monitor.opentelemetry.exporter").setLevel(logging.WARNING)
6
+ from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
7
+ from opentelemetry import _logs as logs
8
+ from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
9
+ from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
10
+ from opentelemetry.sdk.resources import SERVICE_NAME, Resource
17
11
 
12
+ logger = logging.getLogger(__name__)
13
+ logger.addHandler(StreamHandler())
18
14
 
19
- def get_logger(name: str):
20
- """Get a logger instance.
15
+ # Suppress verbose logging from Azure SDK and infrastructure
16
+ _NOISY_LOGGERS = [
17
+ "azure.core.pipeline.policies.http_logging_policy",
18
+ "azure.data.tables",
19
+ "azure.storage.blob",
20
+ "azure.servicebus",
21
+ "azure.identity",
22
+ "azure.monitor.opentelemetry.exporter",
23
+ "azure_functions_worker",
24
+ "azure.functions",
25
+ "uamqp",
26
+ ]
27
+ for _logger_name in _NOISY_LOGGERS:
28
+ logging.getLogger(_logger_name).setLevel(logging.WARNING)
29
+
30
+ LOGGING_IS_CONFIGURED = False
31
+
32
+
33
+ def configure_logging():
34
+ global LOGGING_IS_CONFIGURED
35
+ if LOGGING_IS_CONFIGURED:
36
+ # logging should only be set up once
37
+ # to avoid duplicated log handling.
38
+ # Global variables is the pattern used
39
+ # by opentelemetry, so we use the same
40
+ return
41
+
42
+ # set up logger provider based on the Azure Function resource
43
+ # (this is make sure App Insights can track the log source correctly)
44
+ # (https://learn.microsoft.com/en-us/azure/azure-monitor/app/opentelemetry-enable?tabs=net#set-the-cloud-role-name-and-the-cloud-role-instance)
45
+ resource = Resource.create({SERVICE_NAME: os.getenv("WEBSITE_SITE_NAME")})
46
+ logs.set_logger_provider(
47
+ LoggerProvider(
48
+ resource=resource,
49
+ )
50
+ )
21
51
 
22
- Logs are correlated with the correct function invocation via Azure Functions'
23
- thread-local storage invocation_id, which is set by the monitor decorator.
52
+ # setup azure monitor log exporter to send telemetry to App Insights
53
+ try:
54
+ log_exporter = AzureMonitorLogExporter()
55
+ except ValueError:
56
+ # if no App Insights instrumentation key is set (e.g. when running unit tests),
57
+ # the exporter creation will fail. In this case we skip it
58
+ logger.warning(
59
+ "Cant set up logging to App Insights, as no instrumentation key is set."
60
+ )
61
+ else:
62
+ log_record_processor = BatchLogRecordProcessor(log_exporter)
63
+ logs.get_logger_provider().add_log_record_processor(log_record_processor)
24
64
 
25
- Args:
26
- name: Logger name, typically __name__
65
+ LOGGING_IS_CONFIGURED = True
27
66
 
28
- Returns:
29
- A configured logger instance
30
- """
67
+
68
+ def get_logger(name: str):
69
+ # set up standard logger
31
70
  logger = logging.getLogger(name)
32
71
  logger.setLevel(logging.INFO)
72
+
73
+ if not logger.hasHandlers():
74
+ # add OTEL handler
75
+ handler = LoggingHandler()
76
+ logger.addHandler(handler)
77
+
33
78
  return logger
@@ -1,106 +1,66 @@
1
1
  import logging
2
2
  import os
3
3
  from contextlib import contextmanager
4
+ from logging import StreamHandler
4
5
 
5
- from azure.core.settings import settings
6
6
  from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
7
7
  from opentelemetry import context, trace
8
8
  from opentelemetry.sdk.resources import SERVICE_NAME, Resource
9
- from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, TracerProvider
9
+ from opentelemetry.sdk.trace import TracerProvider
10
10
  from opentelemetry.sdk.trace.export import BatchSpanProcessor
11
11
  from opentelemetry.sdk.trace.sampling import ALWAYS_ON
12
12
  from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
13
13
 
14
- # Enable OpenTelemetry tracing for Azure SDK (including Service Bus)
15
- # This must be set before any Azure SDK clients are created
16
- settings.tracing_implementation = "opentelemetry"
17
-
18
14
  logger = logging.getLogger(__name__)
15
+ logger.addHandler(StreamHandler())
19
16
 
20
- _TRACING_IS_CONFIGURED = False
21
-
22
- # Span name prefixes to allow from Azure SDK (Service Bus for function chaining)
23
- _ALLOWED_AZURE_SPAN_NAMES = frozenset({"ServiceBus.message"})
24
-
25
-
26
- class AzureSDKTraceFilter(SpanProcessor):
27
- """SpanProcessor that filters out noisy Azure SDK traces.
28
-
29
- Allows:
30
- - All non-Azure SDK spans (custom/user traces)
31
- - Service Bus spans (for tracing function chains)
32
-
33
- Drops:
34
- - Other Azure SDK spans (HTTP client, blob storage, etc.)
35
- """
36
-
37
- def __init__(self, wrapped_processor: SpanProcessor):
38
- self.wrapped_processor = wrapped_processor
39
-
40
- def on_start(
41
- self, span: ReadableSpan, parent_context: context.Context = None
42
- ) -> None:
43
- self.wrapped_processor.on_start(span, parent_context)
44
-
45
- def on_end(self, span: ReadableSpan) -> None:
46
- scope = span.instrumentation_scope
47
- if scope and scope.name:
48
- # Check if it's an Azure SDK span (uses azure.core.tracing wrapper)
49
- if scope.name.startswith("azure."):
50
- # Allow only specific Service Bus span names
51
- span_name = getattr(span, "name", "") or ""
52
- if span_name in _ALLOWED_AZURE_SPAN_NAMES:
53
- self.wrapped_processor.on_end(span)
54
- # Drop other Azure SDK spans
55
- return
56
-
57
- # Pass through: non-Azure SDK spans (custom traces)
58
- self.wrapped_processor.on_end(span)
17
+ tracer = trace.get_tracer(__name__)
59
18
 
60
- def shutdown(self) -> None:
61
- self.wrapped_processor.shutdown()
62
-
63
- def force_flush(self, timeout_millis: int = 30000) -> bool:
64
- return self.wrapped_processor.force_flush(timeout_millis)
19
+ TRACING_IS_CONFIGURED = False
65
20
 
66
21
 
67
22
  def configure_tracing():
68
- """Configure OpenTelemetry tracing with Azure Monitor exporter.
69
-
70
- This sets up tracing for Service Bus and custom spans.
71
- Other Azure SDK traces (HTTP, blob, etc.) are filtered out.
72
-
73
- Should be called once before any tracing is performed.
74
- """
75
- global _TRACING_IS_CONFIGURED
76
- if _TRACING_IS_CONFIGURED:
23
+ global TRACING_IS_CONFIGURED
24
+ if TRACING_IS_CONFIGURED:
25
+ # tracing should only be set up once
26
+ # to avoid duplicated trace handling.
27
+ # Global variables is the pattern used
28
+ # by opentelemetry, so we use the same
77
29
  return
78
30
 
79
- # Set up tracer provider with Azure Function resource info
31
+ # set up tracer provider based on the Azure Function resource
32
+ # (this is make sure App Insights can track the trace source correctly)
33
+ # (https://learn.microsoft.com/en-us/azure/azure-monitor/app/opentelemetry-enable?tabs=net#set-the-cloud-role-name-and-the-cloud-role-instance).
34
+ # We use the ALWAYS ON sampler since otherwise spans will not be
35
+ # recording upon creation
36
+ # (https://anecdotes.dev/opentelemetry-on-google-cloud-unraveling-the-mystery-f61f044c18be)
80
37
  resource = Resource.create({SERVICE_NAME: os.getenv("WEBSITE_SITE_NAME")})
81
- provider = TracerProvider(
82
- sampler=ALWAYS_ON,
83
- resource=resource,
38
+ trace.set_tracer_provider(
39
+ TracerProvider(
40
+ sampler=ALWAYS_ON,
41
+ resource=resource,
42
+ )
84
43
  )
85
- trace.set_tracer_provider(provider)
86
44
 
87
- # Set up Azure Monitor trace exporter with filter
45
+ # setup azure monitor trace exporter to send telemetry to App Insights
88
46
  try:
89
47
  trace_exporter = AzureMonitorTraceExporter()
90
- span_processor = BatchSpanProcessor(trace_exporter)
91
- filtered_processor = AzureSDKTraceFilter(span_processor)
92
- provider.add_span_processor(filtered_processor)
93
48
  except ValueError:
49
+ # if no App Insights instrumentation key is set (e.g. when running unit tests),
50
+ # the exporter creation will fail. In this case we skip it
94
51
  logger.warning(
95
- "Cannot set up tracing to App Insights, as no instrumentation key is set."
52
+ "Cant set up tracing to App Insights, as no instrumentation key is set."
96
53
  )
54
+ else:
55
+ span_processor = BatchSpanProcessor(trace_exporter)
56
+ trace.get_tracer_provider().add_span_processor(span_processor)
97
57
 
98
- _TRACING_IS_CONFIGURED = True
58
+ TRACING_IS_CONFIGURED = True
99
59
 
100
60
 
101
61
  @contextmanager
102
62
  def set_trace_context(trace_parent: str, trace_state: str = ""):
103
- """Context manager for setting the trace context.
63
+ """Context manager for setting the trace context
104
64
 
105
65
  Args:
106
66
  trace_parent (str): Trace parent ID
@@ -109,11 +69,11 @@ def set_trace_context(trace_parent: str, trace_state: str = ""):
109
69
  carrier = {"traceparent": trace_parent, "tracestate": trace_state}
110
70
  ctx = TraceContextTextMapPropagator().extract(carrier=carrier)
111
71
 
112
- token = context.attach(ctx)
72
+ token = context.attach(ctx) # attach context before run
113
73
  try:
114
74
  yield
115
75
  finally:
116
- context.detach(token)
76
+ context.detach(token) # detach context after run
117
77
 
118
78
 
119
79
  def get_tracer(name: str):
@@ -140,3 +100,25 @@ def get_current_diagnostic_id() -> str:
140
100
  diagnostic_id = f"00-{operation_id}-{parent_id}-01"
141
101
 
142
102
  return diagnostic_id
103
+
104
+
105
+ # Service Bus trace constants (these were removed from azure-servicebus SDK)
106
+ _SB_TRACE_NAMESPACE = "Microsoft.ServiceBus"
107
+
108
+
109
+ @contextmanager
110
+ def servicebus_send_span(subject: str) -> trace.Span:
111
+ """Start span for Service Bus message tracing.
112
+
113
+ Args:
114
+ subject: The message subject (used as span name for easy identification)
115
+
116
+ Yields:
117
+ trace.Span: the span
118
+ """
119
+ with tracer.start_as_current_span(
120
+ subject, kind=trace.SpanKind.PRODUCER
121
+ ) as msg_span:
122
+ msg_span.set_attributes({"az.namespace": _SB_TRACE_NAMESPACE})
123
+
124
+ yield msg_span
@@ -125,20 +125,20 @@ class WarpzoneEventClient:
125
125
  ):
126
126
  typeguard.check_type(value=topic, expected_type=Topic)
127
127
  topic_name = topic.value
128
+ with traces.servicebus_send_span(event_msg.subject):
129
+ diagnostic_id = traces.get_current_diagnostic_id()
130
+
131
+ az_sdk_msg = ServiceBusMessage(
132
+ body=json.dumps(event_msg.event),
133
+ subject=event_msg.subject,
134
+ content_type="application/json",
135
+ message_id=event_msg.message_id,
136
+ application_properties={"Diagnostic-Id": diagnostic_id},
137
+ time_to_live=event_msg.time_to_live,
138
+ )
128
139
 
129
- diagnostic_id = traces.get_current_diagnostic_id()
130
-
131
- az_sdk_msg = ServiceBusMessage(
132
- body=json.dumps(event_msg.event),
133
- subject=event_msg.subject,
134
- content_type="application/json",
135
- message_id=event_msg.message_id,
136
- application_properties={"Diagnostic-Id": diagnostic_id},
137
- time_to_live=event_msg.time_to_live,
138
- )
139
-
140
- with self._get_topic_sender(topic_name) as sender:
141
- sender.send_messages(message=az_sdk_msg)
140
+ with self._get_topic_sender(topic_name) as sender:
141
+ sender.send_messages(message=az_sdk_msg)
142
142
 
143
143
  def list_subscriptions(
144
144
  self,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: warpzone-sdk
3
- Version: 15.0.0.dev10
3
+ Version: 15.0.0.dev11
4
4
  Summary: The main objective of this package is to centralize logic used to interact with Azure Functions, Azure Service Bus and Azure Table Storage
5
5
  Author: Team Enigma
6
6
  Author-email: enigma@energinet.dk
@@ -17,7 +17,7 @@ warpzone/function/__init__.py,sha256=rJOZBpWsUgjMc7YtXMJ1rLGm45KB1AhDJ_Y2ISiSISc
17
17
  warpzone/function/checks.py,sha256=B9YqThymf16ac_fVAYKilv20ru5v9nwXgHlbxYIaG98,1018
18
18
  warpzone/function/functionize.py,sha256=bSV0QvwKbD9Vo3a_8cc1rgV2rzTdMMvidinyXItBfvs,2128
19
19
  warpzone/function/integrations.py,sha256=sDt2BTx6a4mVc-33wTITP9XQVPustwj7rkX4urTyOqo,4018
20
- warpzone/function/monitor.py,sha256=7GySRig9mI-BtGHm_l5anhmICNjOybgR3MrVhht1ZY8,2065
20
+ warpzone/function/monitor.py,sha256=szPn6jYfWcdypZVjqy3Md7SKpKoZ979PZ8px4PFIm5U,2223
21
21
  warpzone/function/process.py,sha256=nbUVywM8ChfUwuaqFisgaD98aNRgeZkK4g5sbtuBdRs,2339
22
22
  warpzone/function/processors/__init__.py,sha256=DhIdSWLBcIeSO8IJdxPqGIhgwwnkDN6_Xqwy93BCLeA,46
23
23
  warpzone/function/processors/dependencies.py,sha256=m17BwdKyQEvzCPxpQZpAW5l1uYRIHWmweDz3XJskmpA,1259
@@ -27,13 +27,13 @@ warpzone/function/signature.py,sha256=_ZFDp9wAsSXtha05V5WPNeohwJ3JFh_OADB05FaOQa
27
27
  warpzone/function/types.py,sha256=5m2hRrnLC3eqIlAH5-MM9_wKjMZ6lYawZtCOVStyFuY,724
28
28
  warpzone/healthchecks/__init__.py,sha256=9gc_Mt2szs8sDSwy0V4l3JZ6d9hX41xTpZCkDP2qsY4,2108
29
29
  warpzone/healthchecks/model.py,sha256=mM7DnrirLbUpBPPfi82MUPP654D0eOR2_F65TmzsPD0,1187
30
- warpzone/monitor/__init__.py,sha256=ggI5fIUu-szgC44ICzuOmpYrIoVOKPbsMT3zza9ssD4,87
31
- warpzone/monitor/logs.py,sha256=4TSf5zjkLL1L6SehVxya7mjF54E3hhlnmFSB5Sk1DEc,1264
32
- warpzone/monitor/traces.py,sha256=GNDo8-EwiV1VgS8b60JVKz0MILC1K9buGS1AguZHcPY,4613
30
+ warpzone/monitor/__init__.py,sha256=gXT2cxR4tlZER54zd7D49ZQBVyitLaqj13_cUoILuyM,109
31
+ warpzone/monitor/logs.py,sha256=ED6gyOegDLWIMTau3kzkoNgm90EHkRLDr6tnlmq7nq8,2648
32
+ warpzone/monitor/traces.py,sha256=ARd8IW1BqCRgOXu-A_guOAOGpGvpKhJRTzjJgbAgx5Y,3994
33
33
  warpzone/servicebus/data/__init__.py,sha256=lnc0uiaGLF0qMi_rWhCpRSFvaj0CJEiMCAl6Yqn1ZiA,21
34
34
  warpzone/servicebus/data/client.py,sha256=zECS3JwedhYnDk8PntYgIYpBF_uu9YN38KzpPFK7CKs,6511
35
35
  warpzone/servicebus/events/__init__.py,sha256=lnc0uiaGLF0qMi_rWhCpRSFvaj0CJEiMCAl6Yqn1ZiA,21
36
- warpzone/servicebus/events/client.py,sha256=jv7QXlTc6Ye2PDVWJC3H0zBFtYWlybBoRj2Ssu5-6rw,5477
36
+ warpzone/servicebus/events/client.py,sha256=8v8XsF-2RwzKIi_93IzR_eR-BZTGXXHSuV4P9WCQ3_4,5581
37
37
  warpzone/servicebus/events/triggers.py,sha256=_QuPTBbje7LrBoz0qhhgrtDZOcE6x1S9GNu-WJUQ8bY,2626
38
38
  warpzone/tablestorage/db/__init__.py,sha256=lnc0uiaGLF0qMi_rWhCpRSFvaj0CJEiMCAl6Yqn1ZiA,21
39
39
  warpzone/tablestorage/db/base_client.py,sha256=ropKO6z0UXqBl38NuGYV4VZ_ZFm4w1d84ReOLYoBKLY,2376
@@ -52,6 +52,6 @@ warpzone/tools/copy.py,sha256=5fddotMZkXZO8avzUbGOhvs0cp8mce95pNpy0oPVjnQ,2596
52
52
  warpzone/transform/__init__.py,sha256=ruGa7tl-v4ndlWpULE1jSGU_a4_iRc3V6eyNr5xKP9E,27
53
53
  warpzone/transform/data.py,sha256=Abb8PcrgMbbNCJkkIUdtrTHdlY0OfXid387qw1nDpFY,2362
54
54
  warpzone/transform/schema.py,sha256=nbSQtDMvXkyqGKuwhuFCF0WsEDsaNyoPYpMKvbsKlv8,2423
55
- warpzone_sdk-15.0.0.dev10.dist-info/METADATA,sha256=ZkvvLVc9pluIMkBrCfkiEVw91YXE2_hFsrq0lF4C0YU,7399
56
- warpzone_sdk-15.0.0.dev10.dist-info/WHEEL,sha256=3ny-bZhpXrU6vSQ1UPG34FoxZBp3lVcvK0LkgUz6VLk,88
57
- warpzone_sdk-15.0.0.dev10.dist-info/RECORD,,
55
+ warpzone_sdk-15.0.0.dev11.dist-info/METADATA,sha256=6ItHgs5ALgT2jaV5V9_8tipUiMnzfm_h0ciTcZ79Y_Q,7399
56
+ warpzone_sdk-15.0.0.dev11.dist-info/WHEEL,sha256=3ny-bZhpXrU6vSQ1UPG34FoxZBp3lVcvK0LkgUz6VLk,88
57
+ warpzone_sdk-15.0.0.dev11.dist-info/RECORD,,