atomict 1.2.6__py3-none-any.whl → 1.2.9__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.
atomict/infra/logging.py CHANGED
@@ -1,7 +1,189 @@
1
+ import os
2
+ import time
3
+ import json
4
+ import logging
5
+ import threading
6
+ from queue import Queue
1
7
  from logging.config import dictConfig
8
+ from typing import Optional
9
+ import requests
2
10
 
3
11
 
4
- def config_loggers(prefix: str = '', *args, **kwargs):
12
+ class LokiHandler(logging.Handler):
13
+ """Custom logging handler that sends logs to Loki using requests"""
14
+
15
+ def __init__(self, url: str, task_id: Optional[str] = None, batch_size: int = 100, flush_interval: float = 5.0, auth: Optional[tuple[str, str]] = None):
16
+ super().__init__()
17
+ self.url = url
18
+ self.task_id = task_id
19
+ self.batch_size = batch_size
20
+ self.flush_interval = flush_interval
21
+ self.queue = Queue()
22
+ self.stop_event = threading.Event()
23
+
24
+ if auth is None:
25
+ # Try and get auth from environment variables
26
+ username = os.environ.get("AT_LOGGING_USERNAME")
27
+ password = os.environ.get("AT_LOGGING_PASSWORD")
28
+ if username and password:
29
+ auth = (username, password)
30
+
31
+ # _auth is set once during init and never modified, making it safe to read from any thread
32
+ self._auth = auth
33
+ # Start background thread for batching and sending logs
34
+ self.worker_thread = threading.Thread(target=self._worker, daemon=True)
35
+ self.worker_thread.start()
36
+
37
+ def emit(self, record):
38
+ """Queue log record for sending to Loki"""
39
+ try:
40
+ msg = self.format(record)
41
+
42
+ # Create Loki-compatible log entry
43
+ timestamp = str(int(record.created * 1e9)) # nanoseconds
44
+
45
+ # Build labels
46
+ labels = {
47
+ "job": "python",
48
+ "level": record.levelname.lower(),
49
+ "logger": record.name,
50
+ }
51
+
52
+ if self.task_id:
53
+ labels["task_id"] = self.task_id
54
+
55
+ # Add to queue
56
+ entry = {
57
+ "stream": labels,
58
+ "values": [[timestamp, msg]]
59
+ }
60
+ self.queue.put(entry)
61
+
62
+ except Exception as e:
63
+ print(f"[LokiHandler.emit] ERROR: {e}")
64
+ import traceback
65
+ traceback.print_exc()
66
+ self.handleError(record)
67
+
68
+ def _worker(self):
69
+ """Background worker that batches and sends logs to Loki"""
70
+
71
+ try:
72
+ batch = []
73
+ last_flush = time.time()
74
+
75
+ while not self.stop_event.is_set():
76
+ try:
77
+ # Try to get items from queue with timeout
78
+ timeout = max(0.1, self.flush_interval - (time.time() - last_flush))
79
+
80
+ try:
81
+ item = self.queue.get(timeout=timeout)
82
+ batch.append(item)
83
+ except:
84
+ pass # Queue.get timed out
85
+
86
+ # Check if we should flush
87
+ time_since_flush = time.time() - last_flush
88
+ should_flush = (
89
+ len(batch) >= self.batch_size or
90
+ time_since_flush >= self.flush_interval
91
+ )
92
+
93
+ if should_flush:
94
+ if batch:
95
+ self._send_batch(batch)
96
+ batch = []
97
+ else:
98
+ pass
99
+ last_flush = time.time() # Update last_flush even if batch was empty
100
+
101
+ except Exception as e:
102
+ # Log to stderr to avoid recursion
103
+ import sys
104
+ print(f"[LokiHandler._worker] ERROR in worker: {e}", file=sys.stderr)
105
+ import traceback
106
+ traceback.print_exc()
107
+
108
+ except Exception as e:
109
+ import sys
110
+ print(f"[LokiHandler._worker] FATAL ERROR in worker thread: {e}", file=sys.stderr)
111
+ import traceback
112
+ traceback.print_exc()
113
+
114
+ def _send_batch(self, batch):
115
+ """Send a batch of logs to Loki"""
116
+ try:
117
+ # Merge streams with same labels
118
+ streams_dict = {}
119
+ for item in batch:
120
+ stream_key = json.dumps(item["stream"], sort_keys=True)
121
+ if stream_key not in streams_dict:
122
+ streams_dict[stream_key] = {
123
+ "stream": item["stream"],
124
+ "values": []
125
+ }
126
+ streams_dict[stream_key]["values"].extend(item["values"])
127
+
128
+ # Prepare payload
129
+ payload = {
130
+ "streams": list(streams_dict.values())
131
+ }
132
+
133
+ # Send to Loki
134
+ headers = {
135
+ "Content-Type": "application/json",
136
+ "X-Scope-OrgID": "admin"
137
+ }
138
+
139
+ response = requests.post(
140
+ f"{self.url}/loki/api/v1/push",
141
+ json=payload,
142
+ headers=headers,
143
+ timeout=5,
144
+ auth=self._auth
145
+ )
146
+ response.raise_for_status()
147
+
148
+ except Exception as e:
149
+ # Log to stderr to avoid recursion
150
+ import sys
151
+ print(f"[LokiHandler._send_batch] ERROR sending to Loki: {e}", file=sys.stderr)
152
+
153
+ def close(self):
154
+ """Flush remaining logs and stop the worker thread"""
155
+
156
+ self.stop_event.set()
157
+ # Flush any remaining logs
158
+ remaining = []
159
+ while not self.queue.empty():
160
+ try:
161
+ remaining.append(self.queue.get_nowait())
162
+ except:
163
+ break
164
+ if remaining:
165
+ self._send_batch(remaining)
166
+
167
+ # Wait for worker to finish
168
+ self.worker_thread.join(timeout=1)
169
+ super().close()
170
+
171
+
172
+ def config_loggers(
173
+ prefix: str = '',
174
+ task_id: Optional[str] = None,
175
+ batch_size: int = 10,
176
+ flush_interval: float = 2.0,
177
+ *args,
178
+ **kwargs
179
+ ):
180
+ """Configure loggers with console and optional Loki output
181
+
182
+ Args:
183
+ prefix: Prefix to add to log messages
184
+ task_id: Task ID to include in Loki labels for filtering
185
+ """
186
+ # Base configuration with console handler
5
187
  logging_config = dict(
6
188
  version=1,
7
189
  formatters={
@@ -19,4 +201,27 @@ def config_loggers(prefix: str = '', *args, **kwargs):
19
201
  }
20
202
  }
21
203
  )
204
+
205
+ # Apply the configuration FIRST
22
206
  dictConfig(logging_config)
207
+
208
+ # Add Loki handler if endpoint is configured AFTER dictConfig
209
+ loki_endpoint = os.environ.get("AT_LOGGING_ENDPOINT")
210
+
211
+ if loki_endpoint:
212
+ # Create and configure Loki handler
213
+ loki_handler = LokiHandler(
214
+ url=loki_endpoint,
215
+ task_id=task_id,
216
+ batch_size=batch_size,
217
+ flush_interval=flush_interval,
218
+ )
219
+ loki_handler.setFormatter(logging.Formatter(f"%(levelname)s %(asctime)s {prefix} %(message)s"))
220
+
221
+ # Add to root logger
222
+ logging.getLogger().addHandler(loki_handler)
223
+
224
+ # Also add to specific loggers
225
+ for logger_name in ["atomict.api"]:
226
+ logger = logging.getLogger(logger_name)
227
+ logger.addHandler(loki_handler)