| 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 | from typing import Optional |
| 8 | |
| 9 | from llama_toolchain.telemetry.api import * # noqa: F403 |
| 10 | from .config import ConsoleConfig |
| 11 | |
| 12 | |
| 13 | class ConsoleTelemetryImpl(Telemetry): |
| 14 | def __init__(self, config: ConsoleConfig) -> None: |
| 15 | self.config = config |
| 16 | self.spans = {} |
| 17 | |
| 18 | async def initialize(self) -> None: ... |
| 19 | |
| 20 | async def shutdown(self) -> None: ... |
| 21 | |
| 22 | async def log_event(self, event: Event): |
| 23 | if ( |
| 24 | isinstance(event, StructuredLogEvent) |
| 25 | and event.payload.type == StructuredLogType.SPAN_START.value |
| 26 | ): |
| 27 | self.spans[event.span_id] = event.payload |
| 28 | |
| 29 | names = [] |
| 30 | span_id = event.span_id |
| 31 | while True: |
| 32 | span_payload = self.spans.get(span_id) |
| 33 | if not span_payload: |
| 34 | break |
| 35 | |
| 36 | names = [span_payload.name] + names |
| 37 | span_id = span_payload.parent_span_id |
| 38 | |
| 39 | span_name = ".".join(names) if names else None |
| 40 | |
| 41 | formatted = format_event(event, span_name) |
| 42 | if formatted: |
| 43 | print(formatted) |
| 44 | |
| 45 | async def get_trace(self, trace_id: str) -> Trace: |
| 46 | raise NotImplementedError() |
| 47 | |
| 48 | |
| 49 | COLORS = { |
| 50 | "reset": "\033[0m", |
| 51 | "bold": "\033[1m", |
| 52 | "dim": "\033[2m", |
| 53 | "red": "\033[31m", |
| 54 | "green": "\033[32m", |
| 55 | "yellow": "\033[33m", |
| 56 | "blue": "\033[34m", |
| 57 | "magenta": "\033[35m", |
| 58 | "cyan": "\033[36m", |
| 59 | "white": "\033[37m", |
| 60 | } |
| 61 | |
| 62 | SEVERITY_COLORS = { |
| 63 | LogSeverity.VERBOSE: COLORS["dim"] + COLORS["white"], |
| 64 | LogSeverity.DEBUG: COLORS["cyan"], |
| 65 | LogSeverity.INFO: COLORS["green"], |
| 66 | LogSeverity.WARN: COLORS["yellow"], |
| 67 | LogSeverity.ERROR: COLORS["red"], |
| 68 | LogSeverity.CRITICAL: COLORS["bold"] + COLORS["red"], |
| 69 | } |
| 70 | |
| 71 | |
| 72 | def format_event(event: Event, span_name: str) -> Optional[str]: |
| 73 | timestamp = event.timestamp.strftime("%H:%M:%S.%f")[:-3] |
| 74 | span = "" |
| 75 | if span_name: |
| 76 | span = f"{COLORS['magenta']}[{span_name}]{COLORS['reset']} " |
| 77 | if isinstance(event, UnstructuredLogEvent): |
| 78 | severity_color = SEVERITY_COLORS.get(event.severity, COLORS["reset"]) |
| 79 | return ( |
| 80 | f"{COLORS['dim']}{timestamp}{COLORS['reset']} " |
| 81 | f"{severity_color}[{event.severity.name}]{COLORS['reset']} " |
| 82 | f"{span}" |
| 83 | f"{event.message}" |
| 84 | ) |
| 85 | |
| 86 | elif isinstance(event, StructuredLogEvent): |
| 87 | return None |
| 88 | |
| 89 | return f"Unknown event type: {event}" |