|
| 1 | +import os |
| 2 | +import random |
| 3 | +import threading |
| 4 | +from datetime import datetime, timezone |
| 5 | +from typing import Optional, List, Callable, TYPE_CHECKING, Any |
| 6 | + |
| 7 | +from sentry_sdk.utils import format_timestamp, safe_repr |
| 8 | +from sentry_sdk.envelope import Envelope |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from sentry_sdk._types import Log |
| 12 | + |
| 13 | + |
| 14 | +class LogBatcher: |
| 15 | + MAX_LOGS_BEFORE_FLUSH = 100 |
| 16 | + FLUSH_WAIT_TIME = 5.0 |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + capture_func, # type: Callable[[Envelope], None] |
| 21 | + ): |
| 22 | + # type: (...) -> None |
| 23 | + self._log_buffer = [] # type: List[Log] |
| 24 | + self._capture_func = capture_func |
| 25 | + self._running = True |
| 26 | + self._lock = threading.Lock() |
| 27 | + |
| 28 | + self._flush_event = threading.Event() # type: threading.Event |
| 29 | + |
| 30 | + self._flusher = None # type: Optional[threading.Thread] |
| 31 | + self._flusher_pid = None # type: Optional[int] |
| 32 | + |
| 33 | + def _ensure_thread(self): |
| 34 | + # type: (...) -> bool |
| 35 | + """For forking processes we might need to restart this thread. |
| 36 | + This ensures that our process actually has that thread running. |
| 37 | + """ |
| 38 | + if not self._running: |
| 39 | + return False |
| 40 | + |
| 41 | + pid = os.getpid() |
| 42 | + if self._flusher_pid == pid: |
| 43 | + return True |
| 44 | + |
| 45 | + with self._lock: |
| 46 | + # Recheck to make sure another thread didn't get here and start the |
| 47 | + # the flusher in the meantime |
| 48 | + if self._flusher_pid == pid: |
| 49 | + return True |
| 50 | + |
| 51 | + self._flusher_pid = pid |
| 52 | + |
| 53 | + self._flusher = threading.Thread(target=self._flush_loop) |
| 54 | + self._flusher.daemon = True |
| 55 | + |
| 56 | + try: |
| 57 | + self._flusher.start() |
| 58 | + except RuntimeError: |
| 59 | + # Unfortunately at this point the interpreter is in a state that no |
| 60 | + # longer allows us to spawn a thread and we have to bail. |
| 61 | + self._running = False |
| 62 | + return False |
| 63 | + |
| 64 | + return True |
| 65 | + |
| 66 | + def _flush_loop(self): |
| 67 | + # type: (...) -> None |
| 68 | + while self._running: |
| 69 | + self._flush_event.wait(self.FLUSH_WAIT_TIME + random.random()) |
| 70 | + self._flush_event.clear() |
| 71 | + self._flush() |
| 72 | + |
| 73 | + def add( |
| 74 | + self, |
| 75 | + log, # type: Log |
| 76 | + ): |
| 77 | + # type: (...) -> None |
| 78 | + if not self._ensure_thread() or self._flusher is None: |
| 79 | + return None |
| 80 | + |
| 81 | + with self._lock: |
| 82 | + self._log_buffer.append(log) |
| 83 | + if len(self._log_buffer) >= self.MAX_LOGS_BEFORE_FLUSH: |
| 84 | + self._flush_event.set() |
| 85 | + |
| 86 | + def kill(self): |
| 87 | + # type: (...) -> None |
| 88 | + if self._flusher is None: |
| 89 | + return |
| 90 | + |
| 91 | + self._running = False |
| 92 | + self._flush_event.set() |
| 93 | + self._flusher = None |
| 94 | + |
| 95 | + def flush(self): |
| 96 | + # type: (...) -> None |
| 97 | + self._flush() |
| 98 | + |
| 99 | + @staticmethod |
| 100 | + def _log_to_otel(log): |
| 101 | + # type: (Log) -> Any |
| 102 | + def format_attribute(key, val): |
| 103 | + # type: (str, int | float | str | bool) -> Any |
| 104 | + if isinstance(val, bool): |
| 105 | + return {"key": key, "value": {"boolValue": val}} |
| 106 | + if isinstance(val, int): |
| 107 | + return {"key": key, "value": {"intValue": str(val)}} |
| 108 | + if isinstance(val, float): |
| 109 | + return {"key": key, "value": {"doubleValue": val}} |
| 110 | + if isinstance(val, str): |
| 111 | + return {"key": key, "value": {"stringValue": val}} |
| 112 | + return {"key": key, "value": {"stringValue": safe_repr(val)}} |
| 113 | + |
| 114 | + otel_log = { |
| 115 | + "severityText": log["severity_text"], |
| 116 | + "severityNumber": log["severity_number"], |
| 117 | + "body": {"stringValue": log["body"]}, |
| 118 | + "timeUnixNano": str(log["time_unix_nano"]), |
| 119 | + "attributes": [ |
| 120 | + format_attribute(k, v) for (k, v) in log["attributes"].items() |
| 121 | + ], |
| 122 | + } |
| 123 | + |
| 124 | + if "trace_id" in log: |
| 125 | + otel_log["traceId"] = log["trace_id"] |
| 126 | + |
| 127 | + return otel_log |
| 128 | + |
| 129 | + def _flush(self): |
| 130 | + # type: (...) -> Optional[Envelope] |
| 131 | + |
| 132 | + envelope = Envelope( |
| 133 | + headers={"sent_at": format_timestamp(datetime.now(timezone.utc))} |
| 134 | + ) |
| 135 | + with self._lock: |
| 136 | + for log in self._log_buffer: |
| 137 | + envelope.add_log(self._log_to_otel(log)) |
| 138 | + self._log_buffer.clear() |
| 139 | + if envelope.items: |
| 140 | + self._capture_func(envelope) |
| 141 | + return envelope |
| 142 | + return None |
0 commit comments