pyLogAndOrder 1.0.0__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.
@@ -0,0 +1,19 @@
1
+ """
2
+ pyLogAndOrder - Python utilities for posting custom telemetry to Azure Log Analytics.
3
+
4
+ This package provides utilities for sending custom log events to Azure Log Analytics
5
+ using the Entra-authenticated Azure Monitor Logs Ingestion SDK. It includes:
6
+ - A client for direct API calls
7
+ - A logging.Handler integration for seamless Python logging
8
+ """
9
+
10
+ from .client import LogAnalyticsClient, SendSummary, IngestionError, send_log_analytics_event
11
+ from .handler import LogAnalyticsHandler, LifecycleReport, FailureContext
12
+
13
+ __version__ = "1.0.0"
14
+ __all__ = [
15
+ "LogAnalyticsClient",
16
+ "send_log_analytics_event",
17
+ "LogAnalyticsHandler",
18
+ "SendSummary", "IngestionError", "LifecycleReport", "FailureContext",
19
+ ]
@@ -0,0 +1,93 @@
1
+ """Assertion-source invalidation; Azure Identity still owns access-token caching."""
2
+ import hashlib
3
+ import threading
4
+ import logging
5
+ from contextvars import ContextVar
6
+ from azure.core.pipeline.transport import HttpTransport
7
+
8
+ _OWNED_OPERATION = ContextVar('pylogandorder_owned_credential', default=False)
9
+ _FACTORY_LOCK = threading.Lock()
10
+ _INSTALLED_FACTORY = None
11
+
12
+
13
+ def _ensure_scoped_diagnostics():
14
+ """Preserve the application factory and other threads' SDK diagnostics.
15
+
16
+ Identity failure warnings can contain arbitrary token-endpoint error bodies.
17
+ Scrub SDK records only during our owned credential call, before handlers see
18
+ them. A record factory also covers SDK loggers created lazily during a call.
19
+ """
20
+ global _INSTALLED_FACTORY
21
+ with _FACTORY_LOCK:
22
+ previous = logging.getLogRecordFactory()
23
+ if previous is _INSTALLED_FACTORY:
24
+ return
25
+ def factory(*args, **kwargs):
26
+ record = previous(*args, **kwargs)
27
+ if _OWNED_OPERATION.get() and (record.name.startswith('azure.') or record.name.startswith('msal.')):
28
+ record.msg = 'Credential diagnostic details suppressed by pylogandorder.'
29
+ record.args = ()
30
+ record.exc_info = record.exc_text = record.stack_info = None
31
+ return record
32
+ _INSTALLED_FACTORY = factory
33
+ logging.setLogRecordFactory(factory)
34
+
35
+
36
+ class OwnedCredential:
37
+ """Delegate token algorithms while containing diagnostics from owned calls."""
38
+ def __init__(self, credential): self._credential = credential
39
+ def get_token(self, *scopes, **kwargs):
40
+ _ensure_scoped_diagnostics()
41
+ context = _OWNED_OPERATION.set(True)
42
+ try:
43
+ return self._credential.get_token(*scopes, **kwargs)
44
+ finally:
45
+ _OWNED_OPERATION.reset(context)
46
+ def close(self): self._credential.close()
47
+
48
+
49
+ class _SharedTransport(HttpTransport):
50
+ """Credential instances borrow a transport owned by the outer adapter."""
51
+ def __init__(self, transport): self._transport = transport
52
+ def open(self): self._transport.open()
53
+ def close(self): pass
54
+ def send(self, request, **kwargs): return self._transport.send(request, **kwargs)
55
+ def sleep(self, duration): self._transport.sleep(duration)
56
+ def __enter__(self):
57
+ self.open()
58
+ return self
59
+ def __exit__(self, *args): self.close()
60
+
61
+
62
+ class RotatingWorkloadCredential:
63
+ def __init__(self, factory, token_file, **settings):
64
+ self._factory, self._file, self._settings = factory, token_file, settings
65
+ self._transport = settings.get('transport')
66
+ if self._transport is not None:
67
+ self._settings['transport'] = _SharedTransport(self._transport)
68
+ self._digest = None
69
+ self._credential = None
70
+ self._lock = threading.Lock()
71
+
72
+ def get_token(self, *scopes, **kwargs):
73
+ with self._lock:
74
+ with open(self._file, 'rb') as assertion:
75
+ content = assertion.read(1_000_001)
76
+ if not content or len(content) > 1_000_000:
77
+ raise ValueError('Invalid workload assertion file')
78
+ digest = hashlib.sha256(content).digest()
79
+ if self._credential is None or digest != self._digest:
80
+ credential = self._factory(token_file_path=self._file, **self._settings)
81
+ if self._credential is not None:
82
+ self._credential.close()
83
+ self._credential, self._digest = credential, digest
84
+ return self._credential.get_token(*scopes, **kwargs)
85
+
86
+ def close(self):
87
+ with self._lock:
88
+ if self._credential is not None:
89
+ self._credential.close()
90
+ self._credential = None
91
+ if self._transport is not None:
92
+ self._transport.close()
93
+ self._transport = None
@@ -0,0 +1,110 @@
1
+ """The shared envelope and preflight limits; no network or credentials."""
2
+ import gzip
3
+ import json
4
+ import math
5
+ from datetime import datetime, timezone
6
+
7
+ MAX_BODY = 1_000_000
8
+ MAX_FIELD = 64_000
9
+
10
+
11
+ def _pairs(pairs):
12
+ result = {}
13
+ for key, value in pairs:
14
+ if key in result:
15
+ raise ValueError('Duplicate JSON member')
16
+ result[key] = value
17
+ return result
18
+
19
+
20
+ def _json_value(value):
21
+ if value is None or type(value) in (str, bool, int):
22
+ return value
23
+ if type(value) is float and math.isfinite(value):
24
+ return value
25
+ if type(value) is list:
26
+ return [_json_value(item) for item in value]
27
+ if type(value) is dict and all(type(key) is str for key in value):
28
+ return {key: _json_value(item) for key, item in value.items()}
29
+ raise ValueError('Event contains a non-JSON value')
30
+
31
+
32
+ def normalize(data, now):
33
+ if isinstance(data, str):
34
+ try:
35
+ data = json.loads(data, object_pairs_hook=_pairs)
36
+ except (ValueError, RecursionError):
37
+ raise ValueError('Invalid event JSON') from None
38
+ inputs = data if type(data) is list else [data]
39
+ events = []
40
+ for record in inputs:
41
+ if type(record) is not dict:
42
+ raise ValueError('Every event must be an object')
43
+ record = _json_value(record)
44
+ stamp = record.get('TimeGenerated', now().isoformat())
45
+ try:
46
+ if not isinstance(stamp, str):
47
+ raise ValueError()
48
+ parsed = datetime.fromisoformat(stamp.replace('Z', '+00:00'))
49
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
50
+ raise ValueError()
51
+ stamp = parsed.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
52
+ except (ValueError, OverflowError):
53
+ raise ValueError('TimeGenerated must be an explicit timezone-aware timestamp') from None
54
+ level = record.get('level', 'INFO')
55
+ if not isinstance(level, str):
56
+ raise ValueError('Invalid severity')
57
+ level = {'WARN': 'WARNING', 'FATAL': 'CRITICAL'}.get(level.upper(), level.upper())
58
+ if level not in ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'):
59
+ raise ValueError('Invalid severity')
60
+ if type(record.get('message')) is not str:
61
+ raise ValueError('message must be a string')
62
+ properties = record.get('properties', {})
63
+ if type(properties) is not dict:
64
+ raise ValueError('properties must be an object')
65
+ properties = dict(properties)
66
+ for key, value in record.items():
67
+ if key not in ('TimeGenerated', 'level', 'message', 'properties'):
68
+ if key in properties:
69
+ raise ValueError('Ambiguous contextual member')
70
+ properties[key] = value
71
+ event = dict(TimeGenerated=stamp, level=level, message=record['message'], properties=properties)
72
+ try:
73
+ for value in event.values():
74
+ if len(json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False).encode('utf-8')) > MAX_FIELD:
75
+ raise ValueError('Serialized event field exceeds 64000 bytes')
76
+ except (UnicodeError, RecursionError):
77
+ raise ValueError('Invalid event text or depth') from None
78
+ events.append(event)
79
+ return events
80
+
81
+
82
+ def batches(events):
83
+ """Use the pinned SDK's json.dumps encoding, including array punctuation."""
84
+ result = []
85
+ current: list[dict] = []
86
+ size = 2
87
+ for event in events:
88
+ event_size = len(json.dumps(event).encode('utf-8'))
89
+ if event_size + 2 > MAX_BODY:
90
+ raise ValueError('Single encoded event exceeds request ceiling')
91
+ if current and size + event_size + 2 > MAX_BODY:
92
+ result.append(current)
93
+ current, size = [], 2
94
+ current.append(event)
95
+ size += event_size + (2 if len(current) > 1 else 0)
96
+ if current:
97
+ result.append(current)
98
+ # Gzip can expand very small or incompressible bodies. Split before sending.
99
+ checked = []
100
+ pending = list(reversed(result))
101
+ while pending:
102
+ batch = pending.pop()
103
+ if len(gzip.compress(json.dumps(batch).encode('utf-8'), mtime=0)) > MAX_BODY:
104
+ if len(batch) == 1:
105
+ raise ValueError('Single compressed event exceeds request ceiling')
106
+ middle = len(batch) // 2
107
+ pending.extend([batch[middle:], batch[:middle]])
108
+ else:
109
+ checked.append(batch)
110
+ return checked
@@ -0,0 +1,76 @@
1
+ """One retry owner, installed inside the official SDK pipeline."""
2
+ import uuid
3
+ from dataclasses import dataclass
4
+ from azure.core.exceptions import ServiceRequestError, ServiceResponseError
5
+ from azure.core.pipeline.policies import BearerTokenCredentialPolicy, RetryPolicy
6
+
7
+
8
+ class NoChallengeReplay(BearerTokenCredentialPolicy):
9
+ def on_challenge(self, request, response):
10
+ return False
11
+
12
+
13
+ @dataclass
14
+ class UploadState:
15
+ deadline: float
16
+ ids: list[str]
17
+ started: bool = False
18
+ ambiguous: bool = False
19
+
20
+
21
+ def limit_network_timeouts(request, remaining):
22
+ connect = min(10, remaining / 2)
23
+ request.context.options['connection_timeout'] = connect
24
+ request.context.options['read_timeout'] = min(30, remaining - connect)
25
+
26
+
27
+ def collect_ids(state: UploadState, headers):
28
+ for key in ('x-ms-client-request-id', 'x-ms-request-id', 'request-id'):
29
+ value = headers.get(key)
30
+ try:
31
+ safe = str(uuid.UUID(value))
32
+ except (ValueError, TypeError, AttributeError):
33
+ continue
34
+ if safe not in state.ids:
35
+ state.ids.append(safe)
36
+
37
+
38
+ class MonitorRetry(RetryPolicy):
39
+ def __init__(self, retries, clock, delay, jitter):
40
+ super().__init__(retry_total=retries)
41
+ self.retries, self.clock, self.delay, self.jitter = retries, clock, delay, jitter
42
+
43
+ def send(self, request):
44
+ state: UploadState = request.context.options.pop('lao_state')
45
+ for attempt in range(self.retries + 1):
46
+ remaining = state.deadline - self.clock()
47
+ if remaining <= 0:
48
+ raise ServiceResponseError('Upload deadline reached')
49
+ limit_network_timeouts(request, remaining)
50
+ response = None
51
+ try:
52
+ response = self.next.send(request)
53
+ collect_ids(state, response.http_response.headers)
54
+ status = response.http_response.status_code
55
+ if status not in (429, 500, 502, 503, 504):
56
+ return response
57
+ wait = self.get_retry_after(response) if status == 429 else None
58
+ except (ServiceRequestError, ServiceResponseError):
59
+ if not state.started:
60
+ raise
61
+ state.ambiguous = True
62
+ if attempt == self.retries:
63
+ raise
64
+ wait = None
65
+ if attempt == self.retries:
66
+ return response
67
+ if wait is None:
68
+ wait = min(30, 2 ** attempt + self.jitter())
69
+ remaining = state.deadline - self.clock()
70
+ if wait >= remaining:
71
+ if response is not None:
72
+ return response
73
+ raise ServiceResponseError('Retry delay exceeds deadline')
74
+ if wait > 0:
75
+ self.delay(wait)
76
+ raise ServiceResponseError('Upload retry budget exhausted')
@@ -0,0 +1,173 @@
1
+ """Synchronous canonical-event sender using the Azure ingestion SDK."""
2
+ import os
3
+ import time
4
+ import math
5
+ import random
6
+ import gzip
7
+ import uuid
8
+ from dataclasses import dataclass
9
+ from datetime import datetime, timezone
10
+ from urllib.parse import urlsplit
11
+
12
+ from azure.identity import ClientSecretCredential, WorkloadIdentityCredential
13
+ from azure.monitor.ingestion import LogsIngestionClient
14
+
15
+ from ._events import batches, normalize
16
+ from ._credentials import RotatingWorkloadCredential, OwnedCredential
17
+ from ._policy import MonitorRetry, NoChallengeReplay, UploadState, collect_ids, limit_network_timeouts
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class SendSummary:
22
+ records_total: int = 0
23
+ records_accepted: int = 0
24
+ records_failed: int = 0
25
+ records_unconfirmed: int = 0
26
+ records_not_attempted: int = 0
27
+ batches_accepted: int = 0
28
+ request_ids: tuple[str, ...] = ()
29
+
30
+
31
+ class IngestionError(RuntimeError):
32
+ """Safe failure with an honest partial acceptance summary."""
33
+ def __init__(self, summary, status_code=None):
34
+ cause = {403: 'Check DCR publisher permissions and resource access.',
35
+ 404: 'Check the DCR immutable ID and input stream.',
36
+ 413: 'The service rejected the payload size.'}.get(status_code, 'Check credentials, settings and service availability.')
37
+ super().__init__('Ingestion incomplete. ' + cause)
38
+ self.summary = summary
39
+ self.status_code = status_code
40
+
41
+
42
+ def _setting(value, name):
43
+ return os.getenv(name) if value is None else value
44
+
45
+
46
+ class LogAnalyticsClient:
47
+ """Send the shared envelope; SDK success establishes acceptance, not visibility.
48
+
49
+ Settings use explicit values before LA_* / AZURE_* environment variables.
50
+ credential accepts a caller-owned Azure TokenCredential. transport accepts
51
+ an Azure HttpTransport, supporting deterministic offline behavior tests.
52
+ """
53
+ def __init__(self, *, endpoint=None, dcr_immutable_id=None, stream_name=None,
54
+ tenant_id=None, client_id=None, client_secret=None,
55
+ federated_token_file=None, auth_mode=None, credential=None,
56
+ transport=None, credential_transport=None, max_retries=3, timeout=60.0,
57
+ clock=time.monotonic, delay=time.sleep, jitter=None,
58
+ now=lambda: datetime.now(timezone.utc)):
59
+ self.endpoint = _setting(endpoint, 'LA_INGESTION_ENDPOINT')
60
+ self.dcr_immutable_id = _setting(dcr_immutable_id, 'LA_DCR_IMMUTABLE_ID')
61
+ self.stream_name = _setting(stream_name, 'LA_STREAM_NAME')
62
+ required = {'endpoint/LA_INGESTION_ENDPOINT': self.endpoint,
63
+ 'dcr_immutable_id/LA_DCR_IMMUTABLE_ID': self.dcr_immutable_id,
64
+ 'stream_name/LA_STREAM_NAME': self.stream_name}
65
+ tenant_id = _setting(tenant_id, 'AZURE_TENANT_ID')
66
+ client_id = _setting(client_id, 'AZURE_CLIENT_ID')
67
+ secret = _setting(client_secret, 'AZURE_CLIENT_SECRET')
68
+ token_file = _setting(federated_token_file, 'AZURE_FEDERATED_TOKEN_FILE')
69
+ mode = _setting(auth_mode, 'LA_AUTH_MODE')
70
+ if credential is None:
71
+ required.update({'tenant_id/AZURE_TENANT_ID': tenant_id, 'client_id/AZURE_CLIENT_ID': client_id})
72
+ if mode is None:
73
+ if bool(secret) == bool(token_file):
74
+ required['auth_mode/LA_AUTH_MODE (select workload_identity or client_secret)'] = None
75
+ else:
76
+ mode = 'workload_identity' if token_file else 'client_secret'
77
+ if mode == 'client_secret': required['client_secret/AZURE_CLIENT_SECRET'] = secret
78
+ elif mode == 'workload_identity': required['federated_token_file/AZURE_FEDERATED_TOKEN_FILE'] = token_file
79
+ elif mode is not None: raise ValueError('Invalid auth_mode')
80
+ missing = [key for key, value in required.items() if not isinstance(value, str) or not value.strip()]
81
+ if missing: raise ValueError('Missing configuration: ' + ', '.join(missing))
82
+ try:
83
+ uri = urlsplit(self.endpoint)
84
+ if uri.scheme != 'https' or not uri.hostname or uri.username or uri.password or uri.query or uri.fragment:
85
+ raise ValueError()
86
+ for value in (self.dcr_immutable_id, self.stream_name):
87
+ if any(c in value for c in '/\\?#%') or value in ('.', '..') or any(ord(c) < 33 for c in value):
88
+ raise ValueError()
89
+ except ValueError:
90
+ raise ValueError('Invalid HTTPS endpoint or DCR/stream path component') from None
91
+ if type(max_retries) is not int or max_retries < 0 or not math.isfinite(timeout) or timeout <= 0:
92
+ raise ValueError('Retry count and timeout must be bounded positive values')
93
+ self.endpoint = self.endpoint.rstrip('/')
94
+ self._owns_credential = credential is None
95
+ if credential is None:
96
+ try:
97
+ if mode == 'workload_identity':
98
+ identity_settings = dict(tenant_id=tenant_id, client_id=client_id,
99
+ connection_timeout=min(timeout/4, 10), read_timeout=min(timeout/4, 30), retry_total=0)
100
+ if credential_transport is not None: identity_settings['transport'] = credential_transport
101
+ credential = RotatingWorkloadCredential(WorkloadIdentityCredential, token_file, **identity_settings)
102
+ else:
103
+ credential = ClientSecretCredential(tenant_id, client_id, secret,
104
+ connection_timeout=min(timeout/4, 10), read_timeout=min(timeout/4, 30), retry_total=0)
105
+ except Exception:
106
+ raise ValueError('Credential configuration failed') from None
107
+ credential = OwnedCredential(credential)
108
+ self._credential = credential
109
+ retry = MonitorRetry(max_retries, clock, delay, jitter or random.random)
110
+ self._sdk = LogsIngestionClient(self.endpoint, credential, transport=transport,
111
+ retry_policy=retry, authentication_policy=NoChallengeReplay(credential, 'https://monitor.azure.com/.default'),
112
+ redirect_max=0, logging_enable=False)
113
+ self._now = now
114
+ self._clock = clock
115
+ self._timeout = timeout
116
+ self._closed = False
117
+
118
+ def send_event(self, data):
119
+ """Return SendSummary; terminal failures raise IngestionError.summary."""
120
+ if self._closed: raise ValueError('Client is closed')
121
+ events = normalize(data, self._now)
122
+ chunks = batches(events)
123
+ accepted = 0
124
+ ids: list[str] = []
125
+ deadline = self._clock() + self._timeout
126
+ for index, batch in enumerate(chunks):
127
+ errors: list = []
128
+ state = UploadState(deadline, ids)
129
+ if self._clock() >= deadline:
130
+ raise IngestionError(SendSummary(len(events), accepted,
131
+ records_not_attempted=len(events)-accepted, batches_accepted=index, request_ids=tuple(ids)))
132
+
133
+ def guard(request):
134
+ body = request.http_request.body
135
+ if len(body) > 1_000_000 or len(gzip.decompress(body)) > 1_000_000:
136
+ raise ValueError('SDK serialized body exceeds request ceiling')
137
+ remaining = deadline - self._clock()
138
+ if remaining <= 0:
139
+ raise ValueError('Upload deadline reached before submission')
140
+ limit_network_timeouts(request, remaining)
141
+ collect_ids(state, request.http_request.headers)
142
+ state.started = True
143
+
144
+ try:
145
+ self._sdk.upload(self.dcr_immutable_id, self.stream_name, batch, on_error=errors.append,
146
+ lao_state=state, raw_request_hook=guard,
147
+ headers={'x-ms-client-request-id': str(uuid.uuid4())})
148
+ except Exception as error:
149
+ errors.append(error)
150
+ if errors:
151
+ status = getattr(getattr(errors[0], 'error', errors[0]), 'status_code', None)
152
+ unconfirmed = len(batch) if state.ambiguous else 0
153
+ submitted = len(batch) if state.started else 0
154
+ summary = SendSummary(len(events), accepted, submitted-unconfirmed, unconfirmed,
155
+ len(events) - accepted - submitted, index, tuple(ids))
156
+ raise IngestionError(summary, status) from None
157
+ accepted += len(batch)
158
+ return SendSummary(len(events), accepted, batches_accepted=len(chunks), request_ids=tuple(ids))
159
+
160
+ def close(self):
161
+ if not self._closed:
162
+ self._closed = True
163
+ self._sdk.close()
164
+ if self._owns_credential: self._credential.close()
165
+
166
+ def __enter__(self): return self
167
+ def __exit__(self, *args): self.close()
168
+
169
+
170
+ def send_log_analytics_event(data, **settings):
171
+ """Send once and close owned resources; use a client to reuse credentials."""
172
+ with LogAnalyticsClient(**settings) as client:
173
+ return client.send_event(data)
@@ -0,0 +1,226 @@
1
+ """Bounded logging adapter with one upload owner and observable outcomes."""
2
+ import logging
3
+ import math
4
+ import sys
5
+ import threading
6
+ import time
7
+ import traceback
8
+ from collections import deque
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timezone
11
+
12
+ from ._events import normalize
13
+ from .client import IngestionError, LogAnalyticsClient
14
+
15
+ _STANDARD = set(logging.makeLogRecord({}).__dict__) | {'message', 'asctime', 'extra_fields'}
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class LifecycleReport:
20
+ complete: bool
21
+ target: int
22
+ pending: int
23
+ queued: int
24
+ in_flight_unconfirmed: int
25
+ abandoned_on_close: int
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class FailureContext:
30
+ kind: str
31
+ summary: object = None
32
+
33
+
34
+ class LogAnalyticsHandler(logging.Handler):
35
+ """Queue canonical events for one background worker.
36
+
37
+ max_queue_size bounds waiting records, with at most batch_size more in flight.
38
+ on_error(records, context) receives canonical records and safe failure context.
39
+ Counters describe ingestion acceptance, never query visibility. Injected
40
+ clients remain caller-owned; clients created from settings are owned here.
41
+ """
42
+ def __init__(self, *, client=None, extra_fields=None, max_queue_size=1000,
43
+ batch_size=100, send_interval=5.0, on_error=None,
44
+ flush_timeout=30.0, close_timeout=30.0, diagnostic_interval=60.0,
45
+ clock=time.monotonic, **settings):
46
+ super().__init__()
47
+ if type(max_queue_size) is not int or max_queue_size < 1 or type(batch_size) is not int or batch_size < 1:
48
+ raise ValueError('Queue and batch sizes must be positive integers')
49
+ if any(not math.isfinite(v) or v < 0 for v in (flush_timeout, close_timeout, diagnostic_interval)) or not math.isfinite(send_interval) or send_interval <= 0:
50
+ raise ValueError('Lifecycle/diagnostic deadlines must be finite and send_interval positive')
51
+ self.client = client if client is not None else LogAnalyticsClient(**settings)
52
+ self._owns_client = client is None
53
+ self.extra_fields = normalize({'message': '', 'properties': extra_fields or {}}, lambda: datetime.now(timezone.utc))[0]['properties']
54
+ self._capacity, self._batch_size, self._interval = max_queue_size, batch_size, send_interval
55
+ self._flush_timeout, self._close_timeout = flush_timeout, close_timeout
56
+ self._callback, self._clock = on_error, clock
57
+ self._diagnostic_interval = diagnostic_interval
58
+ self._last_diagnostic: dict[str, float] = {}
59
+ self._local = threading.local()
60
+ self._condition = threading.Condition()
61
+ self._queue: deque[tuple[int, dict]] = deque()
62
+ self._pending = set()
63
+ self._in_flight = []
64
+ self._abandoned_events = []
65
+ self._sequence = 0
66
+ self._closing = False
67
+ self._close_report = None
68
+ self._counts = dict(accepted=0, failed=0, unconfirmed=0,
69
+ dropped_queue_full=0, dropped_invalid=0, dropped_closed=0, abandoned_on_close=0)
70
+ self._worker = threading.Thread(target=self._run, name='pylogandorder-upload', daemon=True)
71
+ self._worker.start()
72
+
73
+ @property
74
+ def counters(self):
75
+ with self._condition:
76
+ return dict(self._counts, queued=len(self._queue), in_flight=len(self._in_flight))
77
+
78
+ def _notify_failure(self, records, kind, summary=None):
79
+ if getattr(self._local, 'reporting', False):
80
+ return
81
+ self._local.reporting = True
82
+ try:
83
+ with self._condition:
84
+ diagnose = self._clock() - self._last_diagnostic.get(kind, float('-inf')) >= self._diagnostic_interval
85
+ if diagnose: self._last_diagnostic[kind] = self._clock()
86
+ if diagnose:
87
+ try: sys.stderr.write('pylogandorder: logging outcome requires attention (' + kind + ').\n')
88
+ except Exception: pass
89
+ if self._callback:
90
+ try: self._callback(records, FailureContext(kind, summary))
91
+ except Exception:
92
+ if diagnose:
93
+ try: sys.stderr.write('pylogandorder: error callback failed.\n')
94
+ except Exception: pass
95
+ finally:
96
+ self._local.reporting = False
97
+
98
+ def emit(self, record):
99
+ if not hasattr(self, '_condition') or getattr(self._local, 'reporting', False):
100
+ return
101
+ try:
102
+ context = dict(self.extra_fields)
103
+ record_fields = getattr(record, 'extra_fields', {})
104
+ if type(record_fields) is not dict:
105
+ raise ValueError('extra_fields must be an object')
106
+ context.update(record_fields)
107
+ context.update({key: value for key, value in record.__dict__.items() if key not in _STANDARD})
108
+ if 'source' in context or 'exception' in context:
109
+ raise ValueError('Generated source and exception fields are reserved')
110
+ context['source'] = dict(module=record.module, file_name=record.filename,
111
+ line_number=record.lineno, thread_name=record.threadName,
112
+ process_name=record.processName, process_pid=record.process, func_name=record.funcName)
113
+ if record.exc_info:
114
+ context['exception'] = ''.join(traceback.format_exception(*record.exc_info))
115
+ # Formatter output may include exception text; keep the contextual copy too.
116
+ event = normalize(dict(TimeGenerated=datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
117
+ level=record.levelname, message=self.format(record), properties=context),
118
+ lambda: datetime.now(timezone.utc))[0]
119
+ except Exception:
120
+ with self._condition: self._counts['dropped_invalid'] += 1
121
+ self._notify_failure([], 'invalid_record')
122
+ return
123
+ with self._condition:
124
+ if self._closing:
125
+ self._counts['dropped_closed'] += 1
126
+ failure = 'closed'
127
+ elif len(self._queue) >= self._capacity:
128
+ self._counts['dropped_queue_full'] += 1
129
+ failure = 'queue_full'
130
+ else:
131
+ self._sequence += 1
132
+ self._queue.append((self._sequence, event))
133
+ self._pending.add(self._sequence)
134
+ self._condition.notify_all()
135
+ return
136
+ self._notify_failure([event], failure)
137
+
138
+ def _run(self):
139
+ try:
140
+ while True:
141
+ with self._condition:
142
+ while not self._queue and not self._closing:
143
+ self._condition.wait(self._interval)
144
+ if not self._queue and self._closing:
145
+ return
146
+ items = [self._queue.popleft() for _ in range(min(self._batch_size, len(self._queue)))]
147
+ self._in_flight = items
148
+ events = [event for _, event in items]
149
+ context = None
150
+ try:
151
+ summary = self.client.send_event(events)
152
+ except IngestionError as error:
153
+ summary = error.summary
154
+ context = ('upload_failed', summary)
155
+ except Exception:
156
+ summary = None
157
+ context = ('upload_unconfirmed', None)
158
+ outcome = (dict(accepted=summary.records_accepted,
159
+ failed=summary.records_failed + summary.records_not_attempted,
160
+ unconfirmed=summary.records_unconfirmed) if summary is not None
161
+ else dict(accepted=0, failed=0, unconfirmed=len(events)))
162
+ with self._condition:
163
+ for key, value in outcome.items(): self._counts[key] += value
164
+ self._pending.difference_update(sequence for sequence, _ in items)
165
+ self._in_flight = []
166
+ self._condition.notify_all()
167
+ if context:
168
+ # Ordered preflight batches ensure confirmed records form a prefix.
169
+ self._notify_failure(events[outcome['accepted']:], *context)
170
+ finally:
171
+ with self._condition:
172
+ abandoned = self._abandoned_events
173
+ if abandoned:
174
+ self._notify_failure(abandoned, 'abandoned_on_close')
175
+ if self._owns_client:
176
+ try: self.client.close()
177
+ except Exception: self._notify_failure([], 'client_close_failed')
178
+
179
+ def _report(self, target):
180
+ pending = sum(sequence <= target for sequence in self._pending)
181
+ return LifecycleReport(not pending, target, pending, len(self._queue),
182
+ len(self._in_flight), self._counts['abandoned_on_close'])
183
+
184
+ def flush(self, timeout=None):
185
+ """Wait for all records admitted before this call, including in-flight work."""
186
+ if not hasattr(self, '_condition'):
187
+ return None
188
+ timeout = self._flush_timeout if timeout is None else timeout
189
+ if not math.isfinite(timeout) or timeout < 0: raise ValueError('Invalid flush timeout')
190
+ deadline = time.monotonic() + timeout
191
+ with self._condition:
192
+ target = self._sequence
193
+ while any(sequence <= target for sequence in self._pending):
194
+ remaining = deadline - time.monotonic()
195
+ if remaining <= 0 or threading.current_thread() is self._worker:
196
+ break
197
+ self._condition.wait(remaining)
198
+ return self._report(target)
199
+
200
+ def close(self, timeout=None):
201
+ """Stop admission and drain once. A deadline never cancels an active upload."""
202
+ if not hasattr(self, '_condition'):
203
+ super().close()
204
+ return None
205
+ timeout = self._close_timeout if timeout is None else timeout
206
+ if not math.isfinite(timeout) or timeout < 0: raise ValueError('Invalid close timeout')
207
+ with self._condition:
208
+ if self._close_report is not None:
209
+ return self._close_report
210
+ self._closing = True
211
+ self._condition.notify_all()
212
+ report = self.flush(timeout)
213
+ with self._condition:
214
+ if self._close_report is not None:
215
+ return self._close_report
216
+ abandoned = [event for _, event in self._queue]
217
+ self._pending.difference_update(sequence for sequence, _ in self._queue)
218
+ self._counts['abandoned_on_close'] += len(abandoned)
219
+ self._abandoned_events = abandoned
220
+ self._queue.clear()
221
+ # Complete only if the drain completed; abandoned work is never success.
222
+ self._close_report = LifecycleReport(report.complete, report.target, report.pending,
223
+ 0, len(self._in_flight), self._counts['abandoned_on_close'])
224
+ self._condition.notify_all()
225
+ super().close()
226
+ return self._close_report
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyLogAndOrder
3
+ Version: 1.0.0
4
+ Summary: Entra-authenticated Azure Monitor Logs Ingestion client and bounded logging handler
5
+ Author: Nedomkull Mathematical Modeling
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Nedomkull-Mathematical-Modeling/pyLogAndOrder
8
+ Project-URL: Repository, https://github.com/Nedomkull-Mathematical-Modeling/pyLogAndOrder
9
+ Keywords: azure,log-analytics,telemetry,logging,monitoring
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: System :: Logging
17
+ Classifier: Topic :: System :: Monitoring
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: azure-monitor-ingestion<1.2,>=1.1.0
22
+ Requires-Dist: azure-identity<2,>=1.27.1
23
+ Requires-Dist: azure-core<2,>=1.41.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest<10,>=8; extra == "dev"
26
+ Requires-Dist: mypy<3,>=1.15; extra == "dev"
27
+ Requires-Dist: build<2,>=1.2; extra == "dev"
28
+ Requires-Dist: twine<8,>=6; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # pyLogAndOrder
32
+
33
+ Send the same event envelope as PowerShell LogAndOrder through Microsoft's
34
+ Azure Monitor Logs Ingestion SDK. Requires Python 3.12 or later; CI covers
35
+ 3.12, 3.13 and 3.14 on Windows and Linux.
36
+
37
+ Version 1.0.0 is a breaking release candidate, pending registry publication.
38
+ For development, install this checkout with `python -m pip install -e ".[dev]"`.
39
+ After publication: `python -m pip install pyLogAndOrder==1.0.0`.
40
+
41
+ ## Configure Azure
42
+
43
+ Create an Entra app registration and service principal. Deploy the shared
44
+ four-column table, Direct DCR and DCR-scoped Monitoring Metrics Publisher role
45
+ into an existing workspace using [deploy/main.bicep](deploy/main.bicep).
46
+ [Deployment instructions](deploy/README.md) include side-by-side migration and
47
+ the irreversible in-place operator alternative. The service-principal object ID
48
+ is different from the application's client ID. Normal library calls never
49
+ provision, migrate or delete Azure resources.
50
+
51
+ Explicit keyword arguments take precedence over these environment settings:
52
+
53
+ | Argument | Environment variable |
54
+ | --- | --- |
55
+ | `endpoint` | `LA_INGESTION_ENDPOINT` |
56
+ | `dcr_immutable_id` | `LA_DCR_IMMUTABLE_ID` |
57
+ | `stream_name` | `LA_STREAM_NAME` |
58
+ | `auth_mode` | `LA_AUTH_MODE` |
59
+ | `tenant_id` | `AZURE_TENANT_ID` |
60
+ | `client_id` | `AZURE_CLIENT_ID` |
61
+ | `federated_token_file` | `AZURE_FEDERATED_TOKEN_FILE` |
62
+ | `client_secret` | `AZURE_CLIENT_SECRET` |
63
+
64
+ Prefer `workload_identity`: configure the application's exact external issuer,
65
+ subject and `api://AzureADTokenExchange` audience, and have your host refresh the
66
+ assertion file. The adapter invalidates Azure Identity's assertion source when
67
+ the file changes; Azure Identity exchanges it for Monitor scope
68
+ `https://monitor.azure.com/.default` and owns token renewal/cache behavior.
69
+ A GitHub job identity does not supply a permanent identity for an unrelated daemon.
70
+ Use explicit `client_secret` mode on hosts without an OIDC issuer. Store secrets
71
+ in the host's secret manager. If both credential sources exist, select a mode;
72
+ OIDC failures never silently switch to a secret. A caller-owned Azure
73
+ `credential` can also be supplied. Such credentials must implement finite token
74
+ acquisition timeouts; the library cannot cancel arbitrary caller code.
75
+
76
+ ## Direct sending
77
+
78
+ ```python
79
+ from pylogandorder import LogAnalyticsClient, IngestionError
80
+
81
+ with LogAnalyticsClient() as client: # settings from the host environment
82
+ result = client.send_event({
83
+ "message": "worker started", "level": "INFO",
84
+ "properties": {"service": "worker", "nested": {"ok": True}},
85
+ })
86
+ print(result.records_accepted)
87
+ ```
88
+
89
+ `send_log_analytics_event(data, **settings)` is a one-shot alternative. A reusable
90
+ client avoids repeated credential initialization. Inputs are dictionaries, lists
91
+ of dictionaries or raw JSON. Output always has `TimeGenerated`, `level`,
92
+ `message`, `properties`. Event time is UTC with six fractional digits and a Z
93
+ suffix; an explicitly supplied time must include a timezone. Severity defaults
94
+ to INFO; WARN/FATAL normalize to WARNING/CRITICAL. Unknown top-level fields move
95
+ into properties. Conflicting members, duplicate JSON keys, unsupported types and
96
+ nonfinite numbers are rejected before sending. Nested values and Unicode survive.
97
+
98
+ Preflight validates the entire input before any upload, enforces 64,000 bytes
99
+ per serialized canonical field and 1,000,000 bytes for both raw/compressed
100
+ requests. Nothing is silently truncated. The SDK performs compression and
101
+ serialization; an SDK pipeline guard checks actual wire sizes. An empty list
102
+ returns zero counts without acquiring a token; configuration is still validated.
103
+
104
+ `SendSummary` contains `records_total`, `records_accepted`, `records_failed`,
105
+ `records_unconfirmed`, `records_not_attempted`, `batches_accepted`, `request_ids`.
106
+ Terminal record counts sum to the total. Terminal failures raise `IngestionError`
107
+ with `.summary` and safe `.status_code`; inspect the summary before replaying.
108
+ The configured SDK retry policy owns at most `max_retries=3` retries after the
109
+ initial attempt, within `timeout=60` seconds. It honors Retry-After on 429,
110
+ uses exponential backoff plus jitter for transient service/network failures,
111
+ and never retries 400/401/403/404/413. Later batches stop after terminal failure.
112
+ Timeouts are uncertain; a later permanent retry rejection cannot disprove earlier
113
+ acceptance. Retrying uncertain events may create duplicates. Acceptance does not
114
+ prove query visibility. No durable storage or exactly-once guarantee is provided.
115
+
116
+ ## Standard logging
117
+
118
+ ```python
119
+ import logging
120
+ from pylogandorder import LogAnalyticsHandler
121
+
122
+ handler = LogAnalyticsHandler(extra_fields={"service": "worker"})
123
+ logger = logging.getLogger("worker")
124
+ logger.setLevel(logging.INFO)
125
+ logger.addHandler(handler)
126
+ logger.info("completed %s", "å", extra={"customer": "example"})
127
+ report = handler.flush(timeout=30)
128
+ logger.removeHandler(handler)
129
+ shutdown = handler.close(timeout=30)
130
+ ```
131
+
132
+ The handler uses occurrence time, severity and formatted message. Source
133
+ metadata and exceptions go under properties; per-record context overrides
134
+ defaults. Generated `source`/`exception` fields are reserved. One worker owns all
135
+ uploads; the waiting queue defaults to 1000 records and at most 100 more are in
136
+ flight. Queue-full and invalid records are dropped visibly. Diagnostics go
137
+ directly to stderr, default to once per minute per category and exclude payloads/credentials. Optional
138
+ `on_error(records, context)` receives affected canonical events and safe context;
139
+ callback exceptions are contained and recursive handler logging is suppressed.
140
+
141
+ `handler.counters` is a thread-safe snapshot of `accepted`, `failed`,
142
+ `unconfirmed`, `dropped_queue_full`, `dropped_invalid`, `dropped_closed`,
143
+ `abandoned_on_close`, `queued` and `in_flight`. Unsubmitted records after a
144
+ terminal batch failure count as failed at the handler, rather than disappearing.
145
+
146
+ `flush` includes every record admitted before its call, including an active
147
+ upload. Its default deadline is 30 seconds. `close` stops admission, drains once
148
+ with a default 30-second deadline and is idempotent. `LifecycleReport` separates
149
+ pending work, abandoned queued events and `in_flight_unconfirmed`. A deadline
150
+ stops waiting; it does not cancel an active SDK request, which may finish later
151
+ and update counters. No concurrent forced resend occurs. Emit after close is
152
+ rejected and diagnosed. Injected clients remain caller-owned; otherwise the
153
+ worker closes its owned client after the active request finishes. Abandoned-event
154
+ callbacks run on that worker after any active upload; they never extend the
155
+ caller's close deadline and may finish later than close returns.
156
+
157
+ ## Migration and verification
158
+
159
+ Version 1.0 removes `workspace_id`, `shared_key`, `log_type`, `time_field` and
160
+ legacy headers/signatures. Replace these with endpoint/DCR/input-stream and
161
+ Entra credentials. Move service/customer/source/exception fields into properties.
162
+ Old KQL suffixes such as `message_s`, `httpStatus_d`, `timestamp_t` do not appear
163
+ in the new schema: update queries and alerts or explicitly map historical data.
164
+ See [COMPATIBILITY.md](COMPATIBILITY.md).
165
+
166
+ Offline verification: `python -m pytest -q` and
167
+ `python -m mypy src --check-untyped-defs --follow-imports=silent`.
168
+ Install Azure CLI and pinned Bicep v0.49.2 for compiled deployment tests.
169
+ Live verification is opt-in: [instructions](docs/live-verification.md).
170
+ Build using `python -m build`; validate metadata using `python -m twine check dist/*`.
171
+ Registry publication requires approval of the exact reviewed wheel/source artifacts.
@@ -0,0 +1,11 @@
1
+ pylogandorder/__init__.py,sha256=lWMiYhI9k1BnjkXy2BmDEQXZ7EpJfqwtlm53G8j4no0,714
2
+ pylogandorder/_credentials.py,sha256=e_WiOLZcCg89pRQCbuvvg5rlSPplVRI2ExH1bVQgQaY,3865
3
+ pylogandorder/_events.py,sha256=s8teIE9uksdOV-pRM5BlpUH9po0X2xVlyo0DPghMl14,4522
4
+ pylogandorder/_policy.py,sha256=HF6h-crNoNQkDjTu5xEuBPeH19jDXvoXynkoqhdv6jw,2876
5
+ pylogandorder/client.py,sha256=jbXSbh7juJ21dW1kA5IwOzcc2O3r_lMu1q01NYVJSVQ,8980
6
+ pylogandorder/handler.py,sha256=4GTHMt_BX9RUWdLvEhT4WKOHgVT2ucUiFQmLhmmMWDs,10920
7
+ pylogandorder-1.0.0.dist-info/licenses/LICENSE,sha256=4DJz4CV-RxGK3EkCjCkX94kbKX-j7qJ7ExPfQeN-LPE,1088
8
+ pylogandorder-1.0.0.dist-info/METADATA,sha256=z64BEhnmoHItNesRFJpeEP0RAEtVNDrenHHOEp5i8V0,8853
9
+ pylogandorder-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ pylogandorder-1.0.0.dist-info/top_level.txt,sha256=q_CUT6j3B4fctYqYVrH-2jv8l3r4AJ-cSGyTQ4dO4gA,14
11
+ pylogandorder-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Nedomkull Mathematical Modeling
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pylogandorder