#[cfg(feature = "logs-api")]
mod api;
mod error_reporting;
mod format;
mod json;
#[cfg(feature = "logs-otlp")]
mod otlp;
#[cfg(feature = "logs-api")]
pub use api::{GcpCloudLoggingApiConfig, GcpCloudLoggingHandle, MonitoredResource};
#[cfg(feature = "logs-otlp")]
pub use otlp::OtlpSink;
use crate::common;
use crate::errors::GcloudObservabilityResult;
#[cfg(feature = "logs-otlp")]
use crate::ids::LogId;
pub use error_reporting::{install_panic_hook, ServiceContext};
use json::JsonSink;
use std::sync::{Once, OnceLock};
use tracing::dispatcher::{Dispatch, WeakDispatch};
use tracing::span;
use tracing::{Event, Subscriber};
use tracing_subscriber::fmt::MakeWriter;
use tracing_subscriber::layer::Context;
use tracing_subscriber::registry::LookupSpan;
use tracing_subscriber::Layer;
enum LogSink {
Json(JsonSink),
#[cfg(feature = "logs-api")]
CloudLoggingApi(api::ApiSink),
#[cfg(feature = "logs-otlp")]
Otlp(OtlpSink),
}
impl LogSink {
fn exports_over_network(&self) -> bool {
match self {
Self::Json(_) => false,
#[cfg(feature = "logs-api")]
Self::CloudLoggingApi(_) => true,
#[cfg(feature = "logs-otlp")]
Self::Otlp(_) => true,
}
}
}
const TRANSPORT_CRATES: [&str; 10] = [
"h2",
"hyper",
"hyper_util",
"tonic",
"tower",
"rustls",
"gcloud_sdk",
"opentelemetry",
"opentelemetry_sdk",
"opentelemetry-otlp",
];
fn is_transport_target(target: &str) -> bool {
target
.split("::")
.next()
.is_some_and(|crate_name| TRANSPORT_CRATES.contains(&crate_name))
}
pub struct GcpCloudLoggingLayerBuilder<S = fn() -> std::io::Stdout> {
google_project_id: String,
with_source_location: bool,
error_reporting: Option<ServiceContext>,
sink: S,
}
impl GcpCloudLoggingLayerBuilder<fn() -> std::io::Stdout> {
pub fn new(google_project_id: impl Into<String>) -> Self {
Self {
google_project_id: google_project_id.into(),
with_source_location: true,
error_reporting: None,
sink: std::io::stdout,
}
}
pub async fn for_default_project_id() -> GcloudObservabilityResult<Self> {
Ok(Self::new(common::detect_google_project_id().await?))
}
}
impl<S> GcpCloudLoggingLayerBuilder<S> {
pub fn with_source_location(mut self, enabled: bool) -> Self {
self.with_source_location = enabled;
self
}
pub fn with_error_reporting(mut self, service: ServiceContext) -> Self {
self.error_reporting = Some(service);
self
}
pub fn with_json_writer<W2>(self, make_writer: W2) -> GcpCloudLoggingLayerBuilder<W2> {
GcpCloudLoggingLayerBuilder {
google_project_id: self.google_project_id,
with_source_location: self.with_source_location,
error_reporting: self.error_reporting,
sink: make_writer,
}
}
#[cfg(feature = "logs-api")]
pub fn with_cloud_logging_api(
self,
config: GcpCloudLoggingApiConfig,
) -> GcpCloudLoggingLayerBuilder<GcpCloudLoggingApiConfig> {
GcpCloudLoggingLayerBuilder {
google_project_id: self.google_project_id,
with_source_location: self.with_source_location,
error_reporting: self.error_reporting,
sink: config,
}
}
#[cfg(feature = "logs-otlp")]
pub fn with_otel_logger_provider(
self,
provider: &opentelemetry_sdk::logs::SdkLoggerProvider,
log_id: LogId,
) -> GcpCloudLoggingLayerBuilder<OtlpSink> {
use opentelemetry::logs::LoggerProvider;
GcpCloudLoggingLayerBuilder {
google_project_id: self.google_project_id,
with_source_location: self.with_source_location,
error_reporting: self.error_reporting,
sink: OtlpSink::new(
provider.logger_with_scope(crate::common::instrumentation_scope()),
log_id,
),
}
}
}
#[cfg(feature = "logs-api")]
impl GcpCloudLoggingLayerBuilder<GcpCloudLoggingApiConfig> {
pub async fn build_async(
self,
) -> GcloudObservabilityResult<(GcpCloudLoggingLayer, GcpCloudLoggingHandle)> {
common::validate_google_project_id(&self.google_project_id)?;
let config = self.sink;
let resource = config.resource_or_default(&self.google_project_id);
let log_name = config.log_name(&self.google_project_id);
let sink = std::sync::Arc::new(api::GcloudLogEntrySink::new().await?);
let (api_sink, handle) = api::spawn(&config, log_name, resource, sink);
Ok((
GcpCloudLoggingLayer {
google_project_id: self.google_project_id,
with_source_location: self.with_source_location,
error_reporting: self.error_reporting,
sink: LogSink::CloudLoggingApi(api_sink),
dispatch: OnceLock::new(),
missing_otel_layer_warned: Once::new(),
},
handle,
))
}
}
#[cfg(feature = "logs-otlp")]
impl GcpCloudLoggingLayerBuilder<OtlpSink> {
pub fn build(self) -> GcloudObservabilityResult<GcpCloudLoggingLayer> {
common::validate_google_project_id(&self.google_project_id)?;
Ok(GcpCloudLoggingLayer {
google_project_id: self.google_project_id,
with_source_location: self.with_source_location,
error_reporting: self.error_reporting,
sink: LogSink::Otlp(self.sink),
dispatch: OnceLock::new(),
missing_otel_layer_warned: Once::new(),
})
}
}
impl<S> GcpCloudLoggingLayerBuilder<S>
where
S: for<'writer> MakeWriter<'writer> + Send + Sync + 'static,
{
pub fn build(self) -> GcloudObservabilityResult<GcpCloudLoggingLayer> {
common::validate_google_project_id(&self.google_project_id)?;
Ok(GcpCloudLoggingLayer {
google_project_id: self.google_project_id,
with_source_location: self.with_source_location,
error_reporting: self.error_reporting,
sink: LogSink::Json(JsonSink::new(self.sink)),
dispatch: OnceLock::new(),
missing_otel_layer_warned: Once::new(),
})
}
}
pub struct GcpCloudLoggingLayer {
google_project_id: String,
with_source_location: bool,
error_reporting: Option<ServiceContext>,
sink: LogSink,
dispatch: OnceLock<WeakDispatch>,
missing_otel_layer_warned: Once,
}
fn current_active_otel_context() -> Option<opentelemetry::Context> {
use opentelemetry::trace::TraceContextExt;
let current = opentelemetry::Context::current();
(current.has_active_span() && current.span().span_context().is_valid()).then_some(current)
}
impl GcpCloudLoggingLayer {
fn warn_missing_otel_layer(&self) {
self.missing_otel_layer_warned.call_once(|| {
eprintln!(
"gcloud-observability: trace correlation is disabled for this event \
because no tracing-opentelemetry layer is registered, or it is registered \
after GcpCloudLoggingLayer; register `tracing_opentelemetry::layer()` first."
);
});
}
}
impl<S> Layer<S> for GcpCloudLoggingLayer
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
{
fn on_register_dispatch(&self, subscriber: &Dispatch) {
let _ = self.dispatch.set(subscriber.downgrade());
}
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
if self.sink.exports_over_network() && is_transport_target(event.metadata().target()) {
return;
}
let resolved_span_id: Option<span::Id> = {
let span = match event.parent() {
Some(id) => ctx.span(id),
None => ctx.lookup_current(),
};
span.map(|span_ref| span_ref.id())
};
let otel_context = resolved_span_id
.as_ref()
.and_then(|span_id| {
self.dispatch
.get()
.and_then(WeakDispatch::upgrade)
.and_then(|dispatch| {
tracing_opentelemetry::get_otel_context(span_id, &dispatch)
})
.or_else(|| {
tracing::dispatcher::get_default(|dispatch| {
tracing_opentelemetry::get_otel_context(span_id, dispatch)
})
})
})
.or_else(current_active_otel_context);
let correlation = match otel_context {
Some(cx) => {
use opentelemetry::trace::TraceContextExt;
let span_context = cx.span().span_context().clone();
span_context.is_valid().then(|| format::TraceCorrelation {
trace_id: span_context.trace_id(),
span_id: span_context.span_id(),
sampled: span_context.is_sampled(),
})
}
None => {
if resolved_span_id.is_some() {
self.warn_missing_otel_layer();
}
None
}
};
let record = format::build_log_record(
event,
&self.google_project_id,
self.with_source_location,
correlation.as_ref(),
self.error_reporting.as_ref(),
);
match &self.sink {
LogSink::Json(sink) => sink.write(&record.fields, event.metadata()),
#[cfg(feature = "logs-api")]
LogSink::CloudLoggingApi(sink) => sink.send(record.fields),
#[cfg(feature = "logs-otlp")]
LogSink::Otlp(sink) => sink.send(
record.fields,
record.exception.as_ref(),
correlation.as_ref(),
),
}
}
}