Elffuss BraidHub

kikocis/llama-stack public

cd38843c2a4c · 6.7 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7import asyncio
8import base64
9import logging
10import queue
11import threading
12import uuid
13from datetime import datetime
14from functools import wraps
15from typing import Any, Dict, List
16
17
18from llama_stack.apis.telemetry import * # noqa: F403
19
20
21def generate_short_uuid(len: int = 12):
22 full_uuid = uuid.uuid4()
23 uuid_bytes = full_uuid.bytes
24 encoded = base64.urlsafe_b64encode(uuid_bytes)
25 return encoded.rstrip(b"=").decode("ascii")[:len]
26
27
28CURRENT_TRACE_CONTEXT = None
29BACKGROUND_LOGGER = None
30
31
32class BackgroundLogger:
33 def __init__(self, api: Telemetry, capacity: int = 1000):
34 self.api = api
35 self.log_queue = queue.Queue(maxsize=capacity)
36 self.worker_thread = threading.Thread(target=self._process_logs, daemon=True)
37 self.worker_thread.start()
38
39 def log_event(self, event):
40 try:
41 self.log_queue.put_nowait(event)
42 except queue.Full:
43 print("Log queue is full, dropping event")
44
45 def _process_logs(self):
46 while True:
47 try:
48 event = self.log_queue.get()
49 # figure out how to use a thread's native loop
50 asyncio.run(self.api.log_event(event))
51 except Exception:
52 import traceback
53
54 traceback.print_exc()
55 print("Error processing log event")
56 finally:
57 self.log_queue.task_done()
58
59 def __del__(self):
60 self.log_queue.join()
61
62
63class TraceContext:
64 spans: List[Span] = []
65
66 def __init__(self, logger: BackgroundLogger, trace_id: str):
67 self.logger = logger
68 self.trace_id = trace_id
69
70 def push_span(self, name: str, attributes: Dict[str, Any] = None):
71 current_span = self.get_current_span()
72 span = Span(
73 span_id=generate_short_uuid(),
74 trace_id=self.trace_id,
75 name=name,
76 start_time=datetime.now(),
77 parent_span_id=current_span.span_id if current_span else None,
78 attributes=attributes,
79 )
80
81 self.logger.log_event(
82 StructuredLogEvent(
83 trace_id=span.trace_id,
84 span_id=span.span_id,
85 timestamp=span.start_time,
86 attributes=span.attributes,
87 payload=SpanStartPayload(
88 name=span.name,
89 parent_span_id=span.parent_span_id,
90 ),
91 )
92 )
93
94 self.spans.append(span)
95
96 def pop_span(self, status: SpanStatus = SpanStatus.OK):
97 span = self.spans.pop()
98 if span is not None:
99 self.logger.log_event(
100 StructuredLogEvent(
101 trace_id=span.trace_id,
102 span_id=span.span_id,
103 timestamp=span.start_time,
104 attributes=span.attributes,
105 payload=SpanEndPayload(
106 status=status,
107 ),
108 )
109 )
110
111 def get_current_span(self):
112 return self.spans[-1] if self.spans else None
113
114
115def setup_logger(api: Telemetry, level: int = logging.INFO):
116 global BACKGROUND_LOGGER
117
118 BACKGROUND_LOGGER = BackgroundLogger(api)
119 logger = logging.getLogger()
120 logger.setLevel(level)
121 logger.addHandler(TelemetryHandler())
122
123
124async def start_trace(name: str, attributes: Dict[str, Any] = None):
125 global CURRENT_TRACE_CONTEXT, BACKGROUND_LOGGER
126
127 if BACKGROUND_LOGGER is None:
128 print("No Telemetry implementation set. Skipping trace initialization...")
129 return
130
131 trace_id = generate_short_uuid()
132 context = TraceContext(BACKGROUND_LOGGER, trace_id)
133 context.push_span(name, {"__root__": True, **(attributes or {})})
134
135 CURRENT_TRACE_CONTEXT = context
136
137
138async def end_trace(status: SpanStatus = SpanStatus.OK):
139 global CURRENT_TRACE_CONTEXT
140
141 context = CURRENT_TRACE_CONTEXT
142 if context is None:
143 return
144
145 context.pop_span(status)
146 CURRENT_TRACE_CONTEXT = None
147
148
149def severity(levelname: str) -> LogSeverity:
150 if levelname == "DEBUG":
151 return LogSeverity.DEBUG
152 elif levelname == "INFO":
153 return LogSeverity.INFO
154 elif levelname == "WARNING":
155 return LogSeverity.WARNING
156 elif levelname == "ERROR":
157 return LogSeverity.ERROR
158 elif levelname == "CRITICAL":
159 return LogSeverity.CRITICAL
160 else:
161 raise ValueError(f"Unknown log level: {levelname}")
162
163
164# TODO: ideally, the actual emitting should be done inside a separate daemon
165# process completely isolated from the server
166class TelemetryHandler(logging.Handler):
167 def emit(self, record: logging.LogRecord):
168 # horrendous hack to avoid logging from asyncio and getting into an infinite loop
169 if record.module in ("asyncio", "selector_events"):
170 return
171
172 global CURRENT_TRACE_CONTEXT, BACKGROUND_LOGGER
173
174 if BACKGROUND_LOGGER is None:
175 raise RuntimeError("Telemetry API not initialized")
176
177 context = CURRENT_TRACE_CONTEXT
178 if context is None:
179 return
180
181 span = context.get_current_span()
182 if span is None:
183 return
184
185 BACKGROUND_LOGGER.log_event(
186 UnstructuredLogEvent(
187 trace_id=span.trace_id,
188 span_id=span.span_id,
189 timestamp=datetime.now(),
190 message=self.format(record),
191 severity=severity(record.levelname),
192 )
193 )
194
195 def close(self):
196 pass
197
198
199def span(name: str, attributes: Dict[str, Any] = None):
200 def decorator(func):
201 @wraps(func)
202 def sync_wrapper(*args, **kwargs):
203 try:
204 global CURRENT_TRACE_CONTEXT
205
206 context = CURRENT_TRACE_CONTEXT
207 if context:
208 context.push_span(name, attributes)
209 result = func(*args, **kwargs)
210 finally:
211 context.pop_span()
212 return result
213
214 @wraps(func)
215 async def async_wrapper(*args, **kwargs):
216 try:
217 global CURRENT_TRACE_CONTEXT
218
219 context = CURRENT_TRACE_CONTEXT
220 if context:
221 context.push_span(name, attributes)
222 result = await func(*args, **kwargs)
223 finally:
224 context.pop_span()
225 return result
226
227 @wraps(func)
228 def wrapper(*args, **kwargs):
229 if asyncio.iscoroutinefunction(func):
230 return async_wrapper(*args, **kwargs)
231 else:
232 return sync_wrapper(*args, **kwargs)
233
234 return wrapper
235
236 return decorator