keepup-admin 0.1.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.

Potentially problematic release.


This version of keepup-admin might be problematic. Click here for more details.

Files changed (86) hide show
  1. keepup/THIRD-PARTY.md +44 -0
  2. keepup/__init__.py +41 -0
  3. keepup/api_versions.py +100 -0
  4. keepup/audit.py +499 -0
  5. keepup/auth/__init__.py +7 -0
  6. keepup/auth/config.py +128 -0
  7. keepup/auth/dependencies.py +485 -0
  8. keepup/auth/dto/__init__.py +0 -0
  9. keepup/auth/dto/token.py +31 -0
  10. keepup/auth/factory.py +28 -0
  11. keepup/auth/login_throttle.py +151 -0
  12. keepup/auth/oidc.py +245 -0
  13. keepup/auth/oidc_policy.py +111 -0
  14. keepup/auth/oidc_routes.py +288 -0
  15. keepup/auth/panel_session.py +220 -0
  16. keepup/auth/permissions.py +59 -0
  17. keepup/auth/providers/__init__.py +0 -0
  18. keepup/auth/providers/base.py +168 -0
  19. keepup/auth/providers/local.py +180 -0
  20. keepup/auth/routes.py +660 -0
  21. keepup/auth/seed_accounts.py +322 -0
  22. keepup/auth/session_lifetime.py +104 -0
  23. keepup/auth/signing_key.py +138 -0
  24. keepup/auth/websocket.py +86 -0
  25. keepup/cluster.py +634 -0
  26. keepup/db.py +663 -0
  27. keepup/events.py +764 -0
  28. keepup/factory.py +484 -0
  29. keepup/instance.py +46 -0
  30. keepup/integrations.py +260 -0
  31. keepup/locks.py +412 -0
  32. keepup/logging_setup.py +690 -0
  33. keepup/metrics.py +818 -0
  34. keepup/metrics_retention.py +376 -0
  35. keepup/modules.py +572 -0
  36. keepup/notification_bus.py +355 -0
  37. keepup/plugins/__init__.py +9 -0
  38. keepup/plugins/admin.py +246 -0
  39. keepup/plugins/base.py +234 -0
  40. keepup/plugins/enablement.py +184 -0
  41. keepup/plugins/registry.py +171 -0
  42. keepup/plugins/route_mask.py +338 -0
  43. keepup/plugins/routes.py +376 -0
  44. keepup/roles.py +17 -0
  45. keepup/scheduler.py +93 -0
  46. keepup/schema.py +295 -0
  47. keepup/sections.json +104 -0
  48. keepup/settings.py +184 -0
  49. keepup/static/css/aos.css +1 -0
  50. keepup/static/css/main_nebula.css +232 -0
  51. keepup/static/css/main_new.css +852 -0
  52. keepup/static/css/tailwind.css +1 -0
  53. keepup/static/index_nebula.html +293 -0
  54. keepup/static/index_new.html +286 -0
  55. keepup/static/js/aos.js +1 -0
  56. keepup/static/js/feather-icons.js +13 -0
  57. keepup/static/js/main_new.js +1861 -0
  58. keepup/static/js/tailwind.js +83 -0
  59. keepup/static/modules/css/background_tasks.css +233 -0
  60. keepup/static/modules/css/cluster.css +16 -0
  61. keepup/static/modules/css/event_manager.css +386 -0
  62. keepup/static/modules/css/integration_logs.css +33 -0
  63. keepup/static/modules/css/metrics.css +115 -0
  64. keepup/static/modules/css/modules.css +189 -0
  65. keepup/static/modules/css/themes.css +563 -0
  66. keepup/static/modules/css/users.css +278 -0
  67. keepup/static/modules/js/background_tasks.js +657 -0
  68. keepup/static/modules/js/chart.js +14 -0
  69. keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
  70. keepup/static/modules/js/cluster.js +363 -0
  71. keepup/static/modules/js/event_manager.js +979 -0
  72. keepup/static/modules/js/integration_logs.js +767 -0
  73. keepup/static/modules/js/metrics.js +908 -0
  74. keepup/static/modules/js/modules.js +1086 -0
  75. keepup/static/modules/js/themes.js +653 -0
  76. keepup/static/modules/js/users.js +784 -0
  77. keepup/tables.py +302 -0
  78. keepup/themes.py +496 -0
  79. keepup/web.py +182 -0
  80. keepup_admin-0.1.0.dist-info/METADATA +117 -0
  81. keepup_admin-0.1.0.dist-info/RECORD +86 -0
  82. keepup_admin-0.1.0.dist-info/WHEEL +5 -0
  83. keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
  84. keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
  85. keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
  86. keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,690 @@
1
+ """Local and remote logging.
2
+
3
+ Application logs are written locally with rotation and, when a collector is
4
+ configured, shipped to it in batches from a background thread. Shipping must
5
+ never be able to hold up a request or bring the process down: every failure
6
+ here is swallowed, and repeated failures put the collector aside for a while
7
+ rather than retrying on the hot path.
8
+
9
+ The collector address and the project name under which logs are filed belong
10
+ to the application -- ``configure()`` is how it supplies them.
11
+ """
12
+
13
+ import asyncio
14
+ import atexit
15
+ import json
16
+ import logging
17
+ import logging.handlers
18
+ import os
19
+ import queue
20
+ import sys
21
+ import threading
22
+ import time
23
+ from datetime import datetime
24
+ from typing import Any, Dict, List
25
+
26
+ import requests
27
+
28
+ from keepup.instance import get_instance_id
29
+
30
+ #: What an application may import from this module. Everything else is
31
+ #: internal and may change without notice -- see doc/keepup.md.
32
+ __all__ = [
33
+ "AsyncRemoteLogHandler",
34
+ "RemoteLogHandler",
35
+ "RemoteLoggerWrapper",
36
+ "configure",
37
+ "create_logger_token",
38
+ "init_remote_logging",
39
+ "setup_logging",
40
+ "setup_remote_logging",
41
+ ]
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ #: Set by the application through configure(); the framework has no project of
46
+ #: its own and no collector to ship to.
47
+ PROJECT_NAME = "keepup"
48
+ REMOTE_LOG_URL = None
49
+ #: The credential the collector expects. It identifies the application to a
50
+ #: service the framework knows nothing about, so it arrives from the
51
+ #: application; the package carries no token of its own. Without it nothing is
52
+ #: shipped -- see flush().
53
+ REMOTE_LOG_TOKEN = None
54
+ REMOTE_FLUSH_INTERVAL = 600
55
+ REMOTE_BATCH_SIZE = 100_000
56
+ LOG_DIR = "logs"
57
+
58
+
59
+ #: See keepup.audit for why None cannot mean "leave it as it was": an
60
+ #: application with no collector must be able to say so.
61
+ _UNSET = object()
62
+
63
+
64
+ def configure(project_name=_UNSET, remote_url=_UNSET, flush_interval=_UNSET,
65
+ batch_size=_UNSET, log_dir=_UNSET, remote_token=_UNSET):
66
+ """Supply the application's logging values before the handlers are built."""
67
+ global PROJECT_NAME, REMOTE_LOG_URL, REMOTE_LOG_TOKEN
68
+ global REMOTE_FLUSH_INTERVAL, REMOTE_BATCH_SIZE, LOG_DIR
69
+ if project_name is not _UNSET and project_name is not None:
70
+ PROJECT_NAME = project_name
71
+ if remote_url is not _UNSET:
72
+ REMOTE_LOG_URL = remote_url
73
+ if remote_token is not _UNSET:
74
+ REMOTE_LOG_TOKEN = remote_token
75
+ if flush_interval is not _UNSET and flush_interval is not None:
76
+ REMOTE_FLUSH_INTERVAL = flush_interval
77
+ if batch_size is not _UNSET and batch_size is not None:
78
+ REMOTE_BATCH_SIZE = batch_size
79
+ if log_dir is not _UNSET and log_dir is not None:
80
+ LOG_DIR = log_dir
81
+
82
+
83
+ class RemoteLoggerWrapper:
84
+ """Buffers log records and ships them to a remote collector."""
85
+
86
+ def __init__(self, remote_url: str = None, flush_interval: int = 120, batch_size: int = 100_000_000):
87
+ # No default address. A package that ships to an address of its own
88
+ # turns "nobody configured a collector" into "shipping quietly fails
89
+ # against a port nothing listens on", which looks the same from the
90
+ # outside and reads as working.
91
+ self.remote_url = remote_url or REMOTE_LOG_URL
92
+ self.flush_interval = flush_interval
93
+ self.batch_size = batch_size
94
+ self.log_queue = queue.Queue()
95
+ self.buffer = []
96
+ self.lock = threading.Lock()
97
+ self.running = True
98
+ self.flush_thread = None
99
+ self.project = self._get_project_name()
100
+ self.version = self._get_version()
101
+ self.instance = get_instance_id()
102
+ self.token = self._get_token()
103
+
104
+ self.remote_available = True
105
+ self.consecutive_failures = 0
106
+ self.max_consecutive_failures = 3
107
+ self.backoff_until = 0
108
+
109
+ if not self.remote_url:
110
+ self.running = False
111
+ logger.info("Remote log shipping is off: the application named no collector.")
112
+ return
113
+
114
+ self._start_flush_thread()
115
+ atexit.register(self.force_flush)
116
+ logger.info(f"RemoteLoggerWrapper initialized. Flush interval: {flush_interval}s, Batch size: {batch_size}")
117
+
118
+ def _get_project_name(self) -> str:
119
+ """Return the project name."""
120
+ try:
121
+ with open('config/modules.json', 'r', encoding='utf-8') as f:
122
+ config = json.load(f)
123
+ return config.get('project_name', PROJECT_NAME)
124
+ except:
125
+ return PROJECT_NAME
126
+
127
+ def _get_version(self) -> str:
128
+ """Return the application version."""
129
+ try:
130
+ with open('static/version.json', 'r', encoding='utf-8') as f:
131
+ version_data = json.load(f)
132
+ return version_data.get('version', '1.0.0')
133
+ except:
134
+ return '1.0.0'
135
+
136
+ def _get_token(self) -> str:
137
+ """Return the collector credential the application configured.
138
+
139
+ Returns:
140
+ The token, or None when the application named none -- in which
141
+ case nothing is shipped.
142
+ """
143
+ return REMOTE_LOG_TOKEN
144
+
145
+ def _start_flush_thread(self):
146
+ """Start the background shipping thread."""
147
+ self.flush_thread = threading.Thread(target=self._flush_worker, daemon=True)
148
+ self.flush_thread.start()
149
+
150
+ def _flush_worker(self):
151
+ """Background task shipping logs periodically."""
152
+ while self.running:
153
+ time.sleep(self.flush_interval)
154
+ try:
155
+ self.flush()
156
+ except Exception as e:
157
+ print(f"Error in flush worker: {str(e)}")
158
+
159
+ def emit(self, record: logging.LogRecord):
160
+ """Queue a log record."""
161
+ try:
162
+ log_entry = self._format_record(record)
163
+ try:
164
+ self.log_queue.put(log_entry, block=False)
165
+ except queue.Full:
166
+ try:
167
+ self.log_queue.get_nowait()
168
+ self.log_queue.put_nowait(log_entry)
169
+ except:
170
+ pass
171
+
172
+ if self.log_queue.qsize() >= self.batch_size:
173
+ threading.Thread(target=self.flush, daemon=True).start()
174
+
175
+ except Exception as e:
176
+ print(f"Error in RemoteLoggerWrapper.emit: {str(e)}")
177
+
178
+ def _format_record(self, record: logging.LogRecord) -> Dict[str, Any]:
179
+ """Format a log record."""
180
+ return {
181
+ "date": datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3],
182
+ "level": record.levelname,
183
+ "message": record.getMessage(),
184
+ "class": record.name
185
+ }
186
+
187
+ def flush(self):
188
+ """Ship the buffered logs to the collector."""
189
+ if not self.remote_url:
190
+ return
191
+
192
+ if not self.remote_available and time.time() < self.backoff_until:
193
+ return
194
+
195
+ if not self.token:
196
+ return
197
+
198
+ with self.lock:
199
+ logs_to_send = []
200
+ batch_count = 0
201
+ while not self.log_queue.empty() and batch_count < self.batch_size:
202
+ try:
203
+ log = self.log_queue.get_nowait()
204
+ logs_to_send.append(log)
205
+ batch_count += 1
206
+ except queue.Empty:
207
+ break
208
+ except Exception:
209
+ break
210
+
211
+ if not logs_to_send:
212
+ return
213
+
214
+ try:
215
+ payload = {
216
+ "project": self.project,
217
+ "version": self.version,
218
+ "instance": self.instance,
219
+ "logs": logs_to_send
220
+ }
221
+
222
+ response = requests.post(
223
+ self.remote_url,
224
+ json=payload,
225
+ headers={
226
+ "Authorization": f"Bearer {self.token}",
227
+ "Content-Type": "application/json"
228
+ },
229
+ timeout=(2, 5)
230
+ )
231
+
232
+ if response.status_code == 200:
233
+ self.consecutive_failures = 0
234
+ self.remote_available = True
235
+ logger.debug(f"Successfully sent {len(logs_to_send)} logs to remote server")
236
+ else:
237
+ self._handle_failure(f"HTTP {response.status_code}")
238
+ self._return_logs_to_queue(logs_to_send)
239
+
240
+ except requests.exceptions.Timeout:
241
+ self._handle_failure("timeout")
242
+ logger.warning(f"Timeout sending logs to {self.remote_url}")
243
+ self._return_logs_to_queue(logs_to_send)
244
+
245
+ except requests.exceptions.ConnectionError as e:
246
+ self._handle_failure("connection error")
247
+ logger.warning(f"Connection error sending logs: {str(e)}")
248
+ self._return_logs_to_queue(logs_to_send)
249
+
250
+ except requests.exceptions.RequestException as e:
251
+ self._handle_failure("request error")
252
+ logger.warning(f"Request error sending logs: {str(e)}")
253
+ self._return_logs_to_queue(logs_to_send)
254
+
255
+ except Exception as e:
256
+ self._handle_failure("unexpected error")
257
+ logger.warning(f"Unexpected error while sending logs: {str(e)}")
258
+ self._return_logs_to_queue(logs_to_send)
259
+
260
+ def _handle_failure(self, error_type: str):
261
+ """Handle a failed delivery."""
262
+ self.consecutive_failures += 1
263
+
264
+ if self.consecutive_failures >= self.max_consecutive_failures:
265
+ self.remote_available = False
266
+ # Exponential backoff: 30s, 1m, 2m, 4m, 8m, ...
267
+ backoff_time = min(30 * (2 ** (self.consecutive_failures - self.max_consecutive_failures)), 480)
268
+ self.backoff_until = time.time() + backoff_time
269
+ logger.warning(f"Remote logging disabled for {backoff_time}s due to {self.consecutive_failures} failures")
270
+
271
+ def _return_logs_to_queue(self, logs: List[Dict]):
272
+ """Put logs back on the queue after a failed delivery."""
273
+ try:
274
+ # Returned to the front of the queue so ordering is preserved.
275
+ temp_queue = queue.Queue()
276
+ for log in logs:
277
+ temp_queue.put(log)
278
+ while not self.log_queue.empty():
279
+ try:
280
+ temp_queue.put(self.log_queue.get_nowait())
281
+ except queue.Empty:
282
+ break
283
+ self.log_queue = temp_queue
284
+ except Exception as e:
285
+ print(f"Error returning logs to queue: {str(e)}")
286
+
287
+ def force_flush(self):
288
+ """Ship every buffered log, called at shutdown."""
289
+ logger.info("Force flushing remote logs before shutdown...")
290
+ self.running = False
291
+
292
+ # Short timeouts: shutdown must not hang on an unreachable collector.
293
+ flush_attempts = 0
294
+ max_attempts = 3
295
+
296
+ while not self.log_queue.empty() and flush_attempts < max_attempts:
297
+ try:
298
+ self.flush()
299
+ flush_attempts += 1
300
+ time.sleep(1)
301
+ except:
302
+ break
303
+
304
+
305
+ class AsyncRemoteLogHandler(logging.Handler):
306
+ """Asynchronous log handler for use inside FastAPI."""
307
+
308
+ def __init__(self, remote_url: str = None, flush_interval: int = 120, batch_size: int = 100):
309
+ super().__init__()
310
+ # See RemoteLoggerWrapper.__init__ for why there is no default address.
311
+ self.remote_url = remote_url or REMOTE_LOG_URL
312
+ self.flush_interval = flush_interval
313
+ self.batch_size = batch_size
314
+ self.buffer = []
315
+ self.lock = asyncio.Lock()
316
+ self.project = self._get_project_name()
317
+ self.version = self._get_version()
318
+ self.instance = get_instance_id()
319
+ self.token = self._get_token()
320
+ self.flush_task = None
321
+ self.running = True
322
+
323
+ self.remote_available = True
324
+ self.consecutive_failures = 0
325
+ self.max_consecutive_failures = 3
326
+ self.backoff_until = 0
327
+ self.max_buffer_size = 10000 # maximum buffer size
328
+
329
+ def _get_project_name(self) -> str:
330
+ try:
331
+ with open('config/modules.json', 'r', encoding='utf-8') as f:
332
+ config = json.load(f)
333
+ return config.get('project_name', PROJECT_NAME)
334
+ except:
335
+ return PROJECT_NAME
336
+
337
+ def _get_version(self) -> str:
338
+ try:
339
+ with open('static/version.json', 'r', encoding='utf-8') as f:
340
+ version_data = json.load(f)
341
+ return version_data.get('version', '1.0.0')
342
+ except:
343
+ return '1.0.0'
344
+
345
+ def _get_token(self) -> str:
346
+ return REMOTE_LOG_TOKEN
347
+
348
+ async def start(self):
349
+ """Start the background task."""
350
+ self.flush_task = asyncio.create_task(self._flush_worker())
351
+
352
+ async def stop(self):
353
+ """Stop the background task."""
354
+ self.running = False
355
+ if self.flush_task:
356
+ self.flush_task.cancel()
357
+ try:
358
+ await self.flush_task
359
+ except asyncio.CancelledError:
360
+ pass
361
+ await self.flush()
362
+
363
+ async def _flush_worker(self):
364
+ """Background task shipping logs periodically."""
365
+ while self.running:
366
+ try:
367
+ await asyncio.sleep(self.flush_interval)
368
+ await self.flush()
369
+ except asyncio.CancelledError:
370
+ break
371
+ except Exception as e:
372
+ # Logged, but the loop keeps running.
373
+ print(f"Error in flush worker: {str(e)}")
374
+
375
+ def emit(self, record):
376
+ """Add a record to the buffer."""
377
+ try:
378
+ log_entry = {
379
+ "date": datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3],
380
+ "level": record.levelname,
381
+ "message": record.getMessage(),
382
+ "class": record.name
383
+ }
384
+
385
+ # Scheduled without awaiting: emit() must never block the caller.
386
+ asyncio.create_task(self._safe_add_to_buffer(log_entry))
387
+
388
+ except Exception as e:
389
+ # Logging must never bring the application down.
390
+ print(f"Error in AsyncRemoteLogHandler.emit: {str(e)}")
391
+
392
+ async def _safe_add_to_buffer(self, log_entry: Dict[str, Any]):
393
+ """Add a record to the buffer, keeping the buffer bounded."""
394
+ try:
395
+ async with self.lock:
396
+ if len(self.buffer) >= self.max_buffer_size:
397
+ # A full buffer drops its oldest records rather than growing without bound.
398
+ self.buffer = self.buffer[-(self.max_buffer_size - 1):]
399
+
400
+ self.buffer.append(log_entry)
401
+
402
+ if len(self.buffer) >= self.batch_size:
403
+ asyncio.create_task(self._safe_send_buffer())
404
+
405
+ except Exception as e:
406
+ print(f"Error adding to buffer: {str(e)}")
407
+
408
+ async def _safe_send_buffer(self):
409
+ """Ship the buffer, swallowing any error."""
410
+ try:
411
+ await self._send_buffer()
412
+ except Exception as e:
413
+ print(f"Error in safe send buffer: {str(e)}")
414
+
415
+ async def _send_buffer(self):
416
+ """Ship the buffer to the collector."""
417
+ if not self.remote_available and time.time() < self.backoff_until:
418
+ return
419
+
420
+ async with self.lock:
421
+ if not self.token or not self.buffer:
422
+ return
423
+
424
+ logs_to_send = self.buffer.copy()
425
+ self.buffer.clear()
426
+
427
+ try:
428
+ import httpx
429
+
430
+ # Short timeouts: log shipping must not stall request handling.
431
+ async with httpx.AsyncClient(
432
+ timeout=httpx.Timeout(3.0, connect=2.0),
433
+ limits=httpx.Limits(max_keepalive_connections=5, max_connections=10)
434
+ ) as client:
435
+
436
+ payload = {
437
+ "project": self.project,
438
+ "version": self.version,
439
+ "instance": self.instance,
440
+ "logs": logs_to_send
441
+ }
442
+
443
+ response = await client.post(
444
+ self.remote_url,
445
+ json=payload,
446
+ headers={"Authorization": f"Bearer {self.token}"}
447
+ )
448
+
449
+ if response.status_code == 200:
450
+ self.consecutive_failures = 0
451
+ self.remote_available = True
452
+ logger.debug(f"Successfully sent {len(logs_to_send)} logs")
453
+ else:
454
+ self._handle_failure(f"HTTP {response.status_code}")
455
+ await self._safe_return_to_buffer(logs_to_send)
456
+
457
+ except httpx.TimeoutException:
458
+ self._handle_failure("timeout")
459
+ logger.warning(f"Timeout sending logs to {self.remote_url}")
460
+ await self._safe_return_to_buffer(logs_to_send)
461
+
462
+ except httpx.ConnectError as e:
463
+ self._handle_failure("connection error")
464
+ logger.warning(f"Connection error sending logs: {str(e)}")
465
+ await self._safe_return_to_buffer(logs_to_send)
466
+
467
+ except httpx.HTTPError as e:
468
+ self._handle_failure("http error")
469
+ logger.warning(f"HTTP error sending logs: {str(e)}")
470
+ await self._safe_return_to_buffer(logs_to_send)
471
+
472
+ except Exception as e:
473
+ self._handle_failure("unexpected error")
474
+ logger.warning(f"Unexpected error sending logs: {str(e)}")
475
+ # On an unexpected error the logs are dropped rather than requeued, which
476
+
477
+ def _handle_failure(self, error_type: str):
478
+ """Handle a failed delivery."""
479
+ self.consecutive_failures += 1
480
+
481
+ if self.consecutive_failures >= self.max_consecutive_failures:
482
+ self.remote_available = False
483
+ # Exponential backoff
484
+ backoff_time = min(30 * (2 ** (self.consecutive_failures - self.max_consecutive_failures)), 480)
485
+ self.backoff_until = time.time() + backoff_time
486
+ logger.warning(f"Remote logging disabled for {backoff_time}s due to failures")
487
+
488
+ async def _safe_return_to_buffer(self, logs: List[Dict]):
489
+ """Put logs back into the buffer, keeping it bounded."""
490
+ try:
491
+ async with self.lock:
492
+ # Returned to the front so ordering is preserved.
493
+ self.buffer = logs + self.buffer
494
+ if len(self.buffer) > self.max_buffer_size:
495
+ self.buffer = self.buffer[:self.max_buffer_size]
496
+ except Exception as e:
497
+ print(f"Error returning logs to buffer: {str(e)}")
498
+
499
+ async def flush(self):
500
+ """Ship every buffered log."""
501
+ try:
502
+ await self._send_buffer()
503
+ except Exception as e:
504
+ logger.error(f"Error in flush: {str(e)}")
505
+
506
+
507
+ def setup_remote_logging(remote_url: str = None, flush_interval: int = 120, batch_size: int = 100):
508
+ """Configure remote logging so that it can never block the application."""
509
+ try:
510
+ remote_handler = RemoteLogHandler(remote_url, flush_interval, batch_size)
511
+
512
+ root_logger = logging.getLogger()
513
+ root_logger.addHandler(remote_handler)
514
+
515
+ logger.info(f"Remote logging configured. URL: {remote_url or 'default'}")
516
+ return remote_handler
517
+
518
+ except Exception as e:
519
+ logger.error(f"Failed to setup remote logging (non-critical): {str(e)}")
520
+ return None
521
+
522
+
523
+ def init_remote_logging(remote_url=None, flush_interval=None, batch_size=None):
524
+ """Initialise remote logging, tolerating any failure.
525
+
526
+ Without a collector address -- neither passed here nor given to
527
+ ``configure()`` -- there is nothing to ship to, and the function does
528
+ nothing rather than inventing a destination.
529
+ """
530
+ try:
531
+ remote_url = remote_url or REMOTE_LOG_URL
532
+ if not remote_url:
533
+ return None
534
+ flush_interval = flush_interval or REMOTE_FLUSH_INTERVAL
535
+ batch_size = batch_size or REMOTE_BATCH_SIZE
536
+
537
+ remote_handler = RemoteLogHandler(remote_url, flush_interval, batch_size)
538
+ logging.getLogger().addHandler(remote_handler)
539
+
540
+ for name in ['uvicorn', 'uvicorn.error', 'fastapi']:
541
+ try:
542
+ logger = logging.getLogger(name)
543
+ if logger and not any(isinstance(h, RemoteLogHandler) for h in logger.handlers):
544
+ logger.addHandler(remote_handler)
545
+ except:
546
+ pass
547
+
548
+ logger.info(f"Remote logging initialized. URL: {remote_url}")
549
+ return remote_handler
550
+
551
+ except Exception as e:
552
+ print(f"WARNING: Remote logging initialization failed (non-critical): {str(e)}")
553
+ return None
554
+
555
+
556
+ class RemoteLogHandler(logging.Handler):
557
+ """Log handler shipping records to a remote collector."""
558
+
559
+ def __init__(self, remote_url: str = None, flush_interval: int = 1200, batch_size: int = 100_000):
560
+ super().__init__()
561
+ self.wrapper = RemoteLoggerWrapper(remote_url, flush_interval, batch_size)
562
+ self.setLevel(logging.INFO)
563
+
564
+ def emit(self, record):
565
+ self.wrapper.emit(record)
566
+
567
+ def close(self):
568
+ self.wrapper.force_flush()
569
+ super().close()
570
+
571
+
572
+ #: The path the shipping address ends with, and what registration lives under
573
+ #: instead. Both are the collector's own layout, so one address is enough for
574
+ #: the two calls and the application is not asked for a second one.
575
+ _SHIPPING_PATH = "/logs"
576
+ _REGISTRATION_PATH = "/admin/applications/register"
577
+
578
+
579
+ def _registration_url():
580
+ """Derive the registration endpoint from the configured shipping address.
581
+
582
+ Returns:
583
+ The registration address, or None when the application named no
584
+ collector.
585
+ """
586
+ if not REMOTE_LOG_URL:
587
+ return None
588
+ if REMOTE_LOG_URL.endswith(_SHIPPING_PATH):
589
+ return REMOTE_LOG_URL[: -len(_SHIPPING_PATH)] + _REGISTRATION_PATH
590
+ return REMOTE_LOG_URL.rstrip("/") + _REGISTRATION_PATH
591
+
592
+
593
+ def create_logger_token(admin_token: str, collector_url: str = None,
594
+ app_name: str = None, description: str = None,
595
+ contact_email: str = None):
596
+ """Register this application with the log collector and keep its token.
597
+
598
+ The collector is a service of the deployment, and the name and description
599
+ it files the application under belong to the application. The framework
600
+ supplies none of the three: it has no collector, no product name and
601
+ nothing to say about itself.
602
+
603
+ Args:
604
+ admin_token: the collector's administrator token.
605
+ collector_url: address of the collector's registration endpoint. When
606
+ omitted, the address the application gave ``configure()`` is used.
607
+ app_name: the name to register under; defaults to the configured
608
+ project name.
609
+ description: what to file the application as.
610
+ contact_email: contact address for the registration.
611
+
612
+ Returns:
613
+ The issued API token, or None when no address is known or the
614
+ collector refused.
615
+ """
616
+ import requests
617
+
618
+ collector_url = collector_url or _registration_url()
619
+ if not collector_url:
620
+ logger.error("Cannot register with the log collector: no address was given.")
621
+ return None
622
+
623
+ response = requests.post(
624
+ collector_url,
625
+ json={
626
+ "name": app_name or PROJECT_NAME,
627
+ "description": description,
628
+ "contact_email": contact_email
629
+ },
630
+ headers={
631
+ "Authorization": f"Bearer {admin_token}",
632
+ "Content-Type": "application/json"
633
+ }
634
+ )
635
+
636
+ if response.status_code == 200:
637
+ token_data = response.json()
638
+ with open('config/logger_token.json', 'w', encoding='utf-8') as f:
639
+ json.dump({
640
+ "token": token_data['api_token'],
641
+ "app_id": token_data['id'],
642
+ "app_name": token_data['name'],
643
+ "created_at": datetime.utcnow().isoformat()
644
+ }, f, indent=2)
645
+
646
+ logger.info(f"Logger token created and saved to config/logger_token.json")
647
+ return token_data['api_token']
648
+ else:
649
+ logger.error(f"Failed to create logger token: {response.text}")
650
+ return None
651
+
652
+
653
+ def setup_logging():
654
+ """Configure logging with file rotation."""
655
+
656
+ formatter = logging.Formatter(
657
+ fmt='%(asctime)s.%(msecs)03d | %(levelname)-8s | %(name)s | %(message)s',
658
+ datefmt='%Y-%m-%d %H:%M:%S'
659
+ )
660
+
661
+ logger = logging.getLogger()
662
+ logger.setLevel(logging.INFO)
663
+
664
+ for handler in logger.handlers[:]:
665
+ handler.close()
666
+ logger.removeHandler(handler)
667
+
668
+ console_handler = logging.StreamHandler(sys.stdout)
669
+ console_handler.setLevel(logging.INFO)
670
+ console_handler.setFormatter(formatter)
671
+ logger.addHandler(console_handler)
672
+
673
+ # The directory the application named, not /tmp. LOG_DIR was declared and
674
+ # then used nowhere, so the log went to a world-readable path with a
675
+ # predictable name: on a host with more than one user, or in a container
676
+ # somebody can get a shell in, that is the whole log of the application
677
+ # (task keepup-13).
678
+ os.makedirs(LOG_DIR, exist_ok=True)
679
+ file_handler = logging.handlers.RotatingFileHandler(
680
+ filename=os.path.join(
681
+ LOG_DIR, f"app_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"),
682
+ encoding='utf-8',
683
+ maxBytes=10 * 1024 * 1024,
684
+ backupCount=5
685
+ )
686
+ file_handler.setLevel(logging.DEBUG)
687
+ file_handler.setFormatter(formatter)
688
+ logger.addHandler(file_handler)
689
+
690
+ return logger