Skip to main content

gcloud_observability/logs/
mod.rs

1//! A [`tracing_subscriber::Layer`] that writes structured log entries for
2//! Google Cloud Logging, correlated to Cloud Trace.
3//!
4//! Correlation reads the span context that `tracing-opentelemetry`'s layer
5//! attaches to each span through its public
6//! [`tracing_opentelemetry::get_otel_context`] API. **Register that layer
7//! before this one** on the subscriber: a layer only sees context attached by
8//! layers registered ahead of it, so registering this layer first, or
9//! omitting the OpenTelemetry layer, silently disables `trace`/`spanId` on
10//! every log line (a warning is printed once to stderr when that happens).
11//! Wrapping this layer in `Option`, `Box<dyn Layer>` or a per-layer filter is
12//! supported and needs no extra step. One caveat: under a scoped
13//! (`tracing::subscriber::with_default`) subscriber with the layer wrapped
14//! that way, correlation instead follows whatever tracing span is currently
15//! entered on the thread, so an event's explicit `parent:` is not honoured in
16//! that specific configuration.
17//!
18//! ```ignore
19//! use gcloud_observability::logs::GcpCloudLoggingLayerBuilder;
20//! use tracing_subscriber::layer::SubscriberExt;
21//!
22//! let log_layer = GcpCloudLoggingLayerBuilder::new(google_project_id).build()?;
23//!
24//! let subscriber = tracing_subscriber::registry::Registry::default()
25//!     .with(tracing_opentelemetry::layer().with_tracer(tracer))
26//!     .with(log_layer);
27//! ```
28//!
29//! An event field passed as a `&dyn Error` keeps its whole `source()` chain, one `Caused by:`
30//! line per source; `error = %err` and `error = ?err` record only the text they format.
31//! [`GcpCloudLoggingLayerBuilder::with_error_reporting`] makes every event at ERROR severity
32//! or above an event Cloud Error Reporting groups, with the code location, the error chain
33//! and a backtrace in `message`; set `RUST_BACKTRACE=1` or `RUST_LIB_BACKTRACE=1` to capture
34//! the backtrace. [`install_panic_hook`] reports panics the same way.
35//!
36//! Three sinks are available and exactly one is chosen when the layer is built:
37//! JSON lines to a writer (default stdout, for hosts whose logging agent
38//! collects them), the Cloud Logging API under the `logs-api` feature (for
39//! hosts with no agent), or an OpenTelemetry logger provider under the
40//! `logs-otlp` feature, which exports to the Google Cloud Telemetry API.
41//! [`GcpCloudLoggingLayer`] holds its sink behind a
42//! private enum rather than a type parameter, so callers compose subscribers
43//! the same way regardless of which sink a layer was built with.
44
45#[cfg(feature = "logs-api")]
46mod api;
47mod error_reporting;
48mod format;
49mod json;
50#[cfg(feature = "logs-otlp")]
51mod otlp;
52
53#[cfg(feature = "logs-api")]
54pub use api::{GcpCloudLoggingApiConfig, GcpCloudLoggingHandle, MonitoredResource};
55
56#[cfg(feature = "logs-otlp")]
57pub use otlp::OtlpSink;
58
59use crate::common;
60use crate::errors::GcloudObservabilityResult;
61#[cfg(feature = "logs-otlp")]
62use crate::ids::LogId;
63pub use error_reporting::{install_panic_hook, ServiceContext};
64use json::JsonSink;
65use std::sync::{Once, OnceLock};
66use tracing::dispatcher::{Dispatch, WeakDispatch};
67use tracing::span;
68use tracing::{Event, Subscriber};
69use tracing_subscriber::fmt::MakeWriter;
70use tracing_subscriber::layer::Context;
71use tracing_subscriber::registry::LookupSpan;
72use tracing_subscriber::Layer;
73
74enum LogSink {
75    Json(JsonSink),
76    #[cfg(feature = "logs-api")]
77    CloudLoggingApi(api::ApiSink),
78    #[cfg(feature = "logs-otlp")]
79    Otlp(OtlpSink),
80}
81
82impl LogSink {
83    fn exports_over_network(&self) -> bool {
84        match self {
85            Self::Json(_) => false,
86            #[cfg(feature = "logs-api")]
87            Self::CloudLoggingApi(_) => true,
88            #[cfg(feature = "logs-otlp")]
89            Self::Otlp(_) => true,
90        }
91    }
92}
93
94/// The crates whose events describe the connection a network sink exports over. At DEBUG
95/// or TRACE every export makes some, and an entry made of one is another export to make.
96/// `opentelemetry-otlp` is spelled with a hyphen because its `otel_warn!` events carry the
97/// package name as their target, not the module path.
98const TRANSPORT_CRATES: [&str; 10] = [
99    "h2",
100    "hyper",
101    "hyper_util",
102    "tonic",
103    "tower",
104    "rustls",
105    "gcloud_sdk",
106    "opentelemetry",
107    "opentelemetry_sdk",
108    "opentelemetry-otlp",
109];
110
111fn is_transport_target(target: &str) -> bool {
112    target
113        .split("::")
114        .next()
115        .is_some_and(|crate_name| TRANSPORT_CRATES.contains(&crate_name))
116}
117
118/// Builds a [`GcpCloudLoggingLayer`].
119///
120/// `S` is the sink the layer is built for: a `MakeWriter` for JSON lines, a
121/// `GcpCloudLoggingApiConfig` (feature `logs-api`) or an `OtlpSink` (feature
122/// `logs-otlp`). Each has its own build method, `build` for JSON lines and
123/// OpenTelemetry, `build_async` for the Cloud Logging API, so a builder
124/// becomes exactly one sink, which the compiler checks rather than a runtime
125/// test.
126pub struct GcpCloudLoggingLayerBuilder<S = fn() -> std::io::Stdout> {
127    google_project_id: String,
128    with_source_location: bool,
129    error_reporting: Option<ServiceContext>,
130    sink: S,
131}
132
133impl GcpCloudLoggingLayerBuilder<fn() -> std::io::Stdout> {
134    /// Starts a builder writing JSON lines to stdout, with source location
135    /// enabled.
136    pub fn new(google_project_id: impl Into<String>) -> Self {
137        Self {
138            google_project_id: google_project_id.into(),
139            with_source_location: true,
140            error_reporting: None,
141            sink: std::io::stdout,
142        }
143    }
144
145    /// Starts a builder for the project of the environment the process runs in, as
146    /// [`gcloud_sdk::GoogleEnvironment::detect_google_project_id`] finds it.
147    pub async fn for_default_project_id() -> GcloudObservabilityResult<Self> {
148        Ok(Self::new(common::detect_google_project_id().await?))
149    }
150}
151
152impl<S> GcpCloudLoggingLayerBuilder<S> {
153    /// Adds `logging.googleapis.com/sourceLocation` (file and line) to every
154    /// log line. Enabled by default.
155    pub fn with_source_location(mut self, enabled: bool) -> Self {
156        self.with_source_location = enabled;
157        self
158    }
159
160    /// Makes every event at ERROR severity or above (including a `severity` field of
161    /// `critical`, `alert` or `emergency`) a Cloud Error Reporting event for `service`.
162    ///
163    /// The entry gets `@type`, `serviceContext`, `context.reportLocation` from the event's
164    /// code location, and `context.httpRequest` when `http_request.*` fields are present. Its
165    /// `message` is the event message and the error's `Display` and `source()` chain on one
166    /// line, `message: outer: middle: root`, then the backtrace, which is captured only when
167    /// `RUST_BACKTRACE` or `RUST_LIB_BACKTRACE` enables it. Errors with the same first line
168    /// are one group in Error Reporting, wherever they were logged.
169    ///
170    /// On the OTLP sink the same keys go in the body, and the `exception.type` and
171    /// `exception.message` attributes are added. A `&dyn Error` has no type name on stable
172    /// Rust, so `exception.type` is set from an `exception.type` event field when there is
173    /// one.
174    pub fn with_error_reporting(mut self, service: ServiceContext) -> Self {
175        self.error_reporting = Some(service);
176        self
177    }
178
179    /// Sets where JSON lines are written. Defaults to [`std::io::stdout`].
180    pub fn with_json_writer<W2>(self, make_writer: W2) -> GcpCloudLoggingLayerBuilder<W2> {
181        GcpCloudLoggingLayerBuilder {
182            google_project_id: self.google_project_id,
183            with_source_location: self.with_source_location,
184            error_reporting: self.error_reporting,
185            sink: make_writer,
186        }
187    }
188
189    /// Switches the layer to write through the Cloud Logging API instead of
190    /// JSON lines. The returned builder has [`Self::build`] replaced by
191    /// `build_async`, so a sink is chosen exactly once and cannot be
192    /// contradicted later.
193    ///
194    /// Events of the crates the writes travel through are not written: those whose target is
195    /// in `h2`, `hyper`, `hyper_util`, `tonic`, `tower`, `rustls`, `gcloud_sdk`,
196    /// `opentelemetry`, `opentelemetry_sdk` or `opentelemetry-otlp`. At DEBUG or TRACE every
197    /// write would make events that are written in turn, without end. The JSON sink writes
198    /// them.
199    #[cfg(feature = "logs-api")]
200    pub fn with_cloud_logging_api(
201        self,
202        config: GcpCloudLoggingApiConfig,
203    ) -> GcpCloudLoggingLayerBuilder<GcpCloudLoggingApiConfig> {
204        GcpCloudLoggingLayerBuilder {
205            google_project_id: self.google_project_id,
206            with_source_location: self.with_source_location,
207            error_reporting: self.error_reporting,
208            sink: config,
209        }
210    }
211
212    /// Switches the layer to send entries through an OpenTelemetry logger
213    /// provider, normally the one
214    /// [`GcpOtlpExporterBuilder::create_logger_provider`](crate::otlp::GcpOtlpExporterBuilder::create_logger_provider)
215    /// builds for the Google Cloud Telemetry API. `log_id` names the log the entries are
216    /// written to, as for the Cloud Logging API sink. The returned builder has a
217    /// synchronous [`Self::build`], and the caller flushes and shuts the provider down.
218    ///
219    /// Flushing and shutting down block the calling thread, and need a Tokio runtime thread
220    /// free to drive the export, so they wait out their timeout without exporting on a
221    /// current-thread runtime. Call them on a multi-threaded runtime, or from a thread outside
222    /// the runtime.
223    ///
224    /// Events of the crates the exports travel through are not sent: those whose target is in
225    /// `h2`, `hyper`, `hyper_util`, `tonic`, `tower`, `rustls`, `gcloud_sdk`, `opentelemetry`,
226    /// `opentelemetry_sdk` or `opentelemetry-otlp`. At DEBUG or TRACE every export would make
227    /// events that are exported in turn, without end. The JSON sink writes them.
228    #[cfg(feature = "logs-otlp")]
229    pub fn with_otel_logger_provider(
230        self,
231        provider: &opentelemetry_sdk::logs::SdkLoggerProvider,
232        log_id: LogId,
233    ) -> GcpCloudLoggingLayerBuilder<OtlpSink> {
234        use opentelemetry::logs::LoggerProvider;
235        GcpCloudLoggingLayerBuilder {
236            google_project_id: self.google_project_id,
237            with_source_location: self.with_source_location,
238            error_reporting: self.error_reporting,
239            sink: OtlpSink::new(
240                provider.logger_with_scope(crate::common::instrumentation_scope()),
241                log_id,
242            ),
243        }
244    }
245}
246
247#[cfg(feature = "logs-api")]
248impl GcpCloudLoggingLayerBuilder<GcpCloudLoggingApiConfig> {
249    /// Connects to the Cloud Logging API and starts the background task that
250    /// writes batches of entries.
251    ///
252    /// Must be called from within a Tokio runtime, whose handle the background
253    /// task is spawned on; the entries are written for as long as that runtime
254    /// lives. The returned handle flushes and stops the task - see
255    /// [`GcpCloudLoggingHandle`], and note that dropping it without calling
256    /// `shutdown` leaves queued entries unwritten.
257    ///
258    /// # Errors
259    ///
260    /// [`InvalidParametersError`] for the field `google_project_id` if it is empty or contains
261    /// `/` or a control character, before the Cloud Logging API is contacted.
262    ///
263    /// [`InvalidParametersError`]: crate::errors::GcloudObservabilityError::InvalidParametersError
264    pub async fn build_async(
265        self,
266    ) -> GcloudObservabilityResult<(GcpCloudLoggingLayer, GcpCloudLoggingHandle)> {
267        common::validate_google_project_id(&self.google_project_id)?;
268        let config = self.sink;
269        let resource = config.resource_or_default(&self.google_project_id);
270        let log_name = config.log_name(&self.google_project_id);
271        let sink = std::sync::Arc::new(api::GcloudLogEntrySink::new().await?);
272        let (api_sink, handle) = api::spawn(&config, log_name, resource, sink);
273        Ok((
274            GcpCloudLoggingLayer {
275                google_project_id: self.google_project_id,
276                with_source_location: self.with_source_location,
277                error_reporting: self.error_reporting,
278                sink: LogSink::CloudLoggingApi(api_sink),
279                dispatch: OnceLock::new(),
280                missing_otel_layer_warned: Once::new(),
281            },
282            handle,
283        ))
284    }
285}
286
287#[cfg(feature = "logs-otlp")]
288impl GcpCloudLoggingLayerBuilder<OtlpSink> {
289    /// Builds the layer. Register it on a subscriber after the
290    /// `tracing-opentelemetry` layer to get trace correlation.
291    ///
292    /// # Errors
293    ///
294    /// [`InvalidParametersError`] for the field `google_project_id` if it is empty or contains
295    /// `/` or a control character.
296    ///
297    /// [`InvalidParametersError`]: crate::errors::GcloudObservabilityError::InvalidParametersError
298    pub fn build(self) -> GcloudObservabilityResult<GcpCloudLoggingLayer> {
299        common::validate_google_project_id(&self.google_project_id)?;
300        Ok(GcpCloudLoggingLayer {
301            google_project_id: self.google_project_id,
302            with_source_location: self.with_source_location,
303            error_reporting: self.error_reporting,
304            sink: LogSink::Otlp(self.sink),
305            dispatch: OnceLock::new(),
306            missing_otel_layer_warned: Once::new(),
307        })
308    }
309}
310
311impl<S> GcpCloudLoggingLayerBuilder<S>
312where
313    S: for<'writer> MakeWriter<'writer> + Send + Sync + 'static,
314{
315    /// Builds the layer. Register it on a subscriber after the
316    /// `tracing-opentelemetry` layer to get trace correlation.
317    ///
318    /// # Errors
319    ///
320    /// [`InvalidParametersError`] for the field `google_project_id` if it is empty or contains
321    /// `/` or a control character.
322    ///
323    /// [`InvalidParametersError`]: crate::errors::GcloudObservabilityError::InvalidParametersError
324    pub fn build(self) -> GcloudObservabilityResult<GcpCloudLoggingLayer> {
325        common::validate_google_project_id(&self.google_project_id)?;
326        Ok(GcpCloudLoggingLayer {
327            google_project_id: self.google_project_id,
328            with_source_location: self.with_source_location,
329            error_reporting: self.error_reporting,
330            sink: LogSink::Json(JsonSink::new(self.sink)),
331            dispatch: OnceLock::new(),
332            missing_otel_layer_warned: Once::new(),
333        })
334    }
335}
336
337/// A [`tracing_subscriber::Layer`] that turns every event into one Cloud
338/// Logging entry.
339pub struct GcpCloudLoggingLayer {
340    google_project_id: String,
341    with_source_location: bool,
342    error_reporting: Option<ServiceContext>,
343    sink: LogSink,
344    // Captured from `on_register_dispatch`, needed because a nested
345    // `tracing::dispatcher::get_default` inside `on_event` is documented to
346    // see `Dispatch::none()` under a scoped (`with_default`) subscriber
347    // instead of the real one. A wrapper between this layer and the
348    // subscriber (`Option`, `Box<dyn Layer>`, a per-layer filter) may not
349    // forward `on_register_dispatch`, though, so `on_event` falls back past
350    // this - to `get_default` (which still works for a *global*-default
351    // subscriber, whose fast path ignores the scoped state) and then to the
352    // ambient OpenTelemetry context - when this is empty.
353    dispatch: OnceLock<WeakDispatch>,
354    missing_otel_layer_warned: Once,
355}
356
357/// The OpenTelemetry context active on this thread, if one is and it names a
358/// valid span. Meaningful even when the caller reached it with no enclosing
359/// tracing span to look up, since `tracing-opentelemetry`'s context
360/// activation (on by default) sets this independently of that layer's own
361/// dispatch or of `tracing`'s per-thread scoped-dispatch state.
362fn current_active_otel_context() -> Option<opentelemetry::Context> {
363    use opentelemetry::trace::TraceContextExt;
364    let current = opentelemetry::Context::current();
365    (current.has_active_span() && current.span().span_context().is_valid()).then_some(current)
366}
367
368impl GcpCloudLoggingLayer {
369    fn warn_missing_otel_layer(&self) {
370        self.missing_otel_layer_warned.call_once(|| {
371            eprintln!(
372                "gcloud-observability: trace correlation is disabled for this event \
373                 because no tracing-opentelemetry layer is registered, or it is registered \
374                 after GcpCloudLoggingLayer; register `tracing_opentelemetry::layer()` first."
375            );
376        });
377    }
378}
379
380impl<S> Layer<S> for GcpCloudLoggingLayer
381where
382    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
383{
384    fn on_register_dispatch(&self, subscriber: &Dispatch) {
385        // Ignored if already set: a layer instance is only ever registered
386        // into one subscriber in practice, and keeping the first dispatch is
387        // as good a choice as any if that assumption is ever violated.
388        let _ = self.dispatch.set(subscriber.downgrade());
389    }
390
391    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
392        if self.sink.exports_over_network() && is_transport_target(event.metadata().target()) {
393            return;
394        }
395
396        // `get_otel_context` locks span extensions internally, so the span id
397        // is copied out and the `SpanRef` borrow is dropped before calling it
398        // - holding the borrow across the call risks a deadlock.
399        let resolved_span_id: Option<span::Id> = {
400            let span = match event.parent() {
401                Some(id) => ctx.span(id),
402                None => ctx.lookup_current(),
403            };
404            span.map(|span_ref| span_ref.id())
405        };
406
407        // Three ways to reach the span context, tried in order, because none
408        // alone covers every way this layer can be composed:
409        // - the dispatch captured in `on_register_dispatch` is `None` when a
410        //   wrapper (`Option`, `Box<dyn Layer>`, a per-layer filter) sits
411        //   between this layer and the subscriber and does not forward that
412        //   call;
413        // - `tracing::dispatcher::get_default` recovers it in that case for a
414        //   global-default subscriber, since its fast path returns the real
415        //   dispatch instead of `Dispatch::none()` even nested inside the
416        //   dispatch that delivered this event;
417        // - neither sees anything under a scoped (`with_default`) subscriber
418        //   with the layer wrapped, so the OpenTelemetry context active on
419        //   this thread - set on span entry by `tracing-opentelemetry`'s
420        //   context activation, unless the caller disabled it - is the last
421        //   resort. It follows the currently entered span rather than an
422        //   event's explicit `parent:`.
423        let otel_context = resolved_span_id
424            .as_ref()
425            .and_then(|span_id| {
426                self.dispatch
427                    .get()
428                    .and_then(WeakDispatch::upgrade)
429                    .and_then(|dispatch| {
430                        tracing_opentelemetry::get_otel_context(span_id, &dispatch)
431                    })
432                    .or_else(|| {
433                        tracing::dispatcher::get_default(|dispatch| {
434                            tracing_opentelemetry::get_otel_context(span_id, dispatch)
435                        })
436                    })
437            })
438            .or_else(current_active_otel_context);
439
440        let correlation = match otel_context {
441            Some(cx) => {
442                use opentelemetry::trace::TraceContextExt;
443                let span_context = cx.span().span_context().clone();
444                span_context.is_valid().then(|| format::TraceCorrelation {
445                    trace_id: span_context.trace_id(),
446                    span_id: span_context.span_id(),
447                    sampled: span_context.is_sampled(),
448                })
449            }
450            None => {
451                if resolved_span_id.is_some() {
452                    self.warn_missing_otel_layer();
453                }
454                None
455            }
456        };
457
458        let record = format::build_log_record(
459            event,
460            &self.google_project_id,
461            self.with_source_location,
462            correlation.as_ref(),
463            self.error_reporting.as_ref(),
464        );
465
466        match &self.sink {
467            LogSink::Json(sink) => sink.write(&record.fields, event.metadata()),
468            #[cfg(feature = "logs-api")]
469            LogSink::CloudLoggingApi(sink) => sink.send(record.fields),
470            #[cfg(feature = "logs-otlp")]
471            LogSink::Otlp(sink) => sink.send(
472                record.fields,
473                record.exception.as_ref(),
474                correlation.as_ref(),
475            ),
476        }
477    }
478}