| 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 | |
| 7 | import asyncio |
| 8 | import base64 |
| 9 | import logging |
| 10 | import queue |
| 11 | import threading |
| 12 | import uuid |
| 13 | from datetime import datetime |
| 14 | from functools import wraps |
| 15 | from typing import Any, Callable, Dict, List |
| 16 | |
| 17 | |
| 18 | from llama_stack.apis.telemetry import * # noqa: F403 |
| 19 | |
| 20 | |
| 21 | def 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 | |
| 28 | CURRENT_TRACE_CONTEXT = None |
| 29 | BACKGROUND_LOGGER = None |
| 30 | |
| 31 | |
| 32 | class 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 | |
| 63 | class 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 | |
| 115 | def 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 | |
| 124 | async 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 | |
| 138 | async 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 | |
| 149 | def 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 |
| 166 | class 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 | |
| 199 | class SpanContextManager: |
| 200 | def __init__(self, name: str, attributes: Dict[str, Any] = None): |
| 201 | self.name = name |
| 202 | self.attributes = attributes |
| 203 | |
| 204 | def __enter__(self): |
| 205 | global CURRENT_TRACE_CONTEXT |
| 206 | context = CURRENT_TRACE_CONTEXT |
| 207 | if context: |
| 208 | context.push_span(self.name, self.attributes) |
| 209 | return self |
| 210 | |
| 211 | def __exit__(self, exc_type, exc_value, traceback): |
| 212 | global CURRENT_TRACE_CONTEXT |
| 213 | context = CURRENT_TRACE_CONTEXT |
| 214 | if context: |
| 215 | context.pop_span() |
| 216 | |
| 217 | async def __aenter__(self): |
| 218 | return self.__enter__() |
| 219 | |
| 220 | async def __aexit__(self, exc_type, exc_value, traceback): |
| 221 | self.__exit__(exc_type, exc_value, traceback) |
| 222 | |
| 223 | def __call__(self, func: Callable): |
| 224 | @wraps(func) |
| 225 | def sync_wrapper(*args, **kwargs): |
| 226 | with self: |
| 227 | return func(*args, **kwargs) |
| 228 | |
| 229 | @wraps(func) |
| 230 | async def async_wrapper(*args, **kwargs): |
| 231 | async with self: |
| 232 | return await func(*args, **kwargs) |
| 233 | |
| 234 | @wraps(func) |
| 235 | def wrapper(*args, **kwargs): |
| 236 | if asyncio.iscoroutinefunction(func): |
| 237 | return async_wrapper(*args, **kwargs) |
| 238 | else: |
| 239 | return sync_wrapper(*args, **kwargs) |
| 240 | |
| 241 | return wrapper |
| 242 | |
| 243 | |
| 244 | def span(name: str, attributes: Dict[str, Any] = None): |
| 245 | return SpanContextManager(name, attributes) |