Skip to main content

a2a_protocol_server/otel/telemetry/
console_format.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! What `install_subscriber` prints to standard error: the text `tracing`
5//! prints by default, or one JSON object per line carrying the trace context
6//! (audit C-06; ADR 0038 ยง6).
7//!
8//! The OpenTelemetry compatibility note "Trace Context in non-OTLP Log
9//! Formats" (`specification/compatibility/logging_trace_context.md`) names
10//! the fields of a log line outside OTLP: `trace_id` and `span_id` as
11//! lower-case hex, and `trace_flags` as two hex digits. They are written
12//! inside a span that has a valid OpenTelemetry context, and left out
13//! elsewhere.
14
15use std::fmt;
16use std::time::SystemTime;
17
18use opentelemetry::trace::TraceContextExt as _;
19use serde_json::{Map, Value};
20use tracing::field::{Field, Visit};
21use tracing_subscriber::fmt::format::Writer;
22use tracing_subscriber::fmt::{FmtContext, FormatEvent, FormatFields};
23use tracing_subscriber::registry::LookupSpan;
24
25use super::config::Notes;
26use super::console::rfc3339;
27
28/// The format of the lines `install_subscriber` prints.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum ConsoleFormat {
32    /// `tracing-subscriber`'s text, as before 0.16.0.
33    #[default]
34    Text,
35    /// One JSON object per line: `timestamp`, `level`, `target`, `message`,
36    /// the event's own fields and, inside a span with an OpenTelemetry
37    /// context, `trace_id`, `span_id` and `trace_flags`.
38    Json,
39}
40
41/// The variable that chooses the format when the code does not.
42pub(super) const VARIABLE: &str = "A2A_LOG_FORMAT";
43
44/// The format `A2A_LOG_FORMAT` names (`json` or `text`, in any case); a
45/// value it does not know is noted and the text format used, as F3 has an
46/// unusable value do.
47pub(super) fn from_env(value: Option<&str>, notes: &Notes) -> ConsoleFormat {
48    match value.map(str::trim) {
49        None | Some("") => ConsoleFormat::Text,
50        Some(v) if v.eq_ignore_ascii_case("json") => ConsoleFormat::Json,
51        Some(v) if v.eq_ignore_ascii_case("text") => ConsoleFormat::Text,
52        Some(v) => {
53            notes.ignored(
54                VARIABLE,
55                v,
56                "is not `json` or `text`",
57                "the text format is used",
58            );
59            ConsoleFormat::Text
60        }
61    }
62}
63
64/// Formats each event as one JSON line.
65pub(super) struct JsonLines;
66
67impl<S, N> FormatEvent<S, N> for JsonLines
68where
69    S: tracing::Subscriber + for<'a> LookupSpan<'a>,
70    N: for<'a> FormatFields<'a> + 'static,
71{
72    fn format_event(
73        &self,
74        _ctx: &FmtContext<'_, S, N>,
75        mut writer: Writer<'_>,
76        event: &tracing::Event<'_>,
77    ) -> fmt::Result {
78        let meta = event.metadata();
79        let mut line = Map::new();
80        line.insert("timestamp".into(), rfc3339(SystemTime::now()).into());
81        line.insert("level".into(), meta.level().as_str().into());
82        line.insert("target".into(), meta.target().into());
83        let mut fields = Fields(Map::new());
84        event.record(&mut fields);
85        let mut fields = fields.0;
86        line.insert(
87            "message".into(),
88            fields
89                .remove("message")
90                .unwrap_or(Value::String(String::new())),
91        );
92        for (key, value) in fields {
93            line.entry(key).or_insert(value);
94        }
95        // `tracing::Span::current()` is the none span here: the dispatcher
96        // is busy delivering this event, and `tracing` hands a re-entrant
97        // lookup no subscriber. The OpenTelemetry context the tracing layer
98        // activates when a span is entered (on by default in
99        // tracing-opentelemetry 0.34) is the one the event happened in.
100        let context = opentelemetry::Context::current();
101        let span = context.span();
102        let span_context = span.span_context();
103        if span_context.is_valid() {
104            line.insert(
105                "trace_id".into(),
106                span_context.trace_id().to_string().into(),
107            );
108            line.insert("span_id".into(), span_context.span_id().to_string().into());
109            line.insert(
110                "trace_flags".into(),
111                format!("{:02x}", span_context.trace_flags().to_u8()).into(),
112            );
113        }
114        writeln!(writer, "{}", Value::Object(line))
115    }
116}
117
118/// An event's fields as JSON values.
119struct Fields(Map<String, Value>);
120
121impl Visit for Fields {
122    fn record_str(&mut self, field: &Field, value: &str) {
123        self.0.insert(field.name().to_owned(), value.into());
124    }
125    fn record_bool(&mut self, field: &Field, value: bool) {
126        self.0.insert(field.name().to_owned(), value.into());
127    }
128    fn record_i64(&mut self, field: &Field, value: i64) {
129        self.0.insert(field.name().to_owned(), value.into());
130    }
131    fn record_u64(&mut self, field: &Field, value: u64) {
132        self.0.insert(field.name().to_owned(), value.into());
133    }
134    fn record_f64(&mut self, field: &Field, value: f64) {
135        self.0.insert(field.name().to_owned(), value.into());
136    }
137    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
138        self.0
139            .insert(field.name().to_owned(), format!("{value:?}").into());
140    }
141}
142
143#[cfg(test)]
144mod tests;