Skip to main content

gcloud_observability/logs/api/
mod.rs

1//! Cloud Logging API sink: configuration, the client that performs
2//! `WriteLogEntries`, and the handle that flushes and stops the background
3//! task.
4//!
5//! Use this sink on hosts with no logging agent to collect stdout. Where an
6//! agent is present the JSON sink is cheaper and more robust: it costs no
7//! queue, no background task and no egress of its own.
8
9mod batcher;
10mod entry;
11
12pub use batcher::GcpCloudLoggingHandle;
13pub(crate) use batcher::{spawn, ApiSink, LogEntrySink};
14
15/// The monitored resource a log entry is attributed to, re-exported so callers
16/// need not depend on `gcloud-sdk` directly.
17pub use gcloud_sdk::google::api::MonitoredResource;
18
19use crate::errors::GcloudObservabilityResult;
20use crate::ids::LogId;
21use gcloud_sdk::google::logging::v2::logging_service_v2_client::LoggingServiceV2Client;
22use gcloud_sdk::google::logging::v2::WriteLogEntriesRequest;
23use gcloud_sdk::{GoogleApi, GoogleAuthMiddleware};
24use std::time::Duration;
25
26const DEFAULT_BATCH_SIZE: usize = 200;
27const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_secs(2);
28const DEFAULT_QUEUE_CAPACITY: usize = 10_000;
29const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
30
31/// How the Cloud Logging API sink writes: which log to write to, what resource
32/// the entries are attributed to, and how aggressively they are batched.
33pub struct GcpCloudLoggingApiConfig {
34    pub(crate) log_id: LogId,
35    pub(crate) resource: Option<MonitoredResource>,
36    pub(crate) batch_size: usize,
37    pub(crate) flush_interval: Duration,
38    pub(crate) queue_capacity: usize,
39    pub(crate) shutdown_timeout: Duration,
40}
41
42impl GcpCloudLoggingApiConfig {
43    /// Writes to `projects/{project}/logs/{log_id}`, with `/` in `log_id` URL-encoded as
44    /// `%2F`, as Cloud Logging stores it.
45    pub fn new(log_id: LogId) -> Self {
46        Self {
47            log_id,
48            resource: None,
49            batch_size: DEFAULT_BATCH_SIZE,
50            flush_interval: DEFAULT_FLUSH_INTERVAL,
51            queue_capacity: DEFAULT_QUEUE_CAPACITY,
52            shutdown_timeout: DEFAULT_SHUTDOWN_TIMEOUT,
53        }
54    }
55
56    /// Attributes every entry to this monitored resource. Defaults to type
57    /// `global` labelled with the project id, which is accepted everywhere;
58    /// set a specific resource (`gce_instance`, `k8s_container`, …) to have
59    /// the entries grouped with the rest of that resource's logs.
60    pub fn with_resource(mut self, resource: MonitoredResource) -> Self {
61        self.resource = Some(resource);
62        self
63    }
64
65    /// Writes as soon as this many entries are queued. Defaults to 200.
66    pub fn with_batch_size(mut self, batch_size: usize) -> Self {
67        self.batch_size = batch_size;
68        self
69    }
70
71    /// Writes a partial batch this long after its first entry was queued.
72    /// Defaults to two seconds.
73    pub fn with_flush_interval(mut self, flush_interval: Duration) -> Self {
74        self.flush_interval = flush_interval;
75        self
76    }
77
78    /// Bounds the queue between the layer and the background task. Events
79    /// recorded when the queue is full are dropped rather than blocking the
80    /// thread that logged them. Defaults to 10 000.
81    pub fn with_queue_capacity(mut self, queue_capacity: usize) -> Self {
82        self.queue_capacity = queue_capacity;
83        self
84    }
85
86    /// Bounds how long [`GcpCloudLoggingHandle::shutdown`] waits for the final
87    /// write. Defaults to five seconds.
88    pub fn with_shutdown_timeout(mut self, shutdown_timeout: Duration) -> Self {
89        self.shutdown_timeout = shutdown_timeout;
90        self
91    }
92
93    /// The `logName` of every entry, in which `[LOG_ID]` must be URL-encoded. `/` is the only
94    /// character of a [`LogId`] that is not URL-safe.
95    pub(crate) fn log_name(&self, google_project_id: &str) -> String {
96        format!(
97            "projects/{google_project_id}/logs/{}",
98            self.log_id.to_string().replace('/', "%2F")
99        )
100    }
101
102    pub(crate) fn resource_or_default(&self, google_project_id: &str) -> MonitoredResource {
103        self.resource.clone().unwrap_or_else(|| MonitoredResource {
104            r#type: "global".to_string(),
105            labels: [("project_id".to_string(), google_project_id.to_string())]
106                .into_iter()
107                .collect(),
108        })
109    }
110}
111
112pub(crate) struct GcloudLogEntrySink {
113    client: GoogleApi<LoggingServiceV2Client<GoogleAuthMiddleware>>,
114}
115
116impl GcloudLogEntrySink {
117    pub(crate) async fn new() -> GcloudObservabilityResult<Self> {
118        let client = GoogleApi::from_function(
119            LoggingServiceV2Client::new,
120            "https://logging.googleapis.com",
121            None,
122        )
123        .await?;
124        Ok(Self { client })
125    }
126}
127
128#[async_trait::async_trait]
129impl LogEntrySink for GcloudLogEntrySink {
130    async fn write(&self, request: WriteLogEntriesRequest) -> Result<(), String> {
131        self.client
132            .get()
133            .write_log_entries(gcloud_sdk::tonic::Request::new(request))
134            .await
135            .map(|_| ())
136            .map_err(|status| status.to_string())
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn slash_of_a_log_id_is_url_encoded_in_the_log_name() {
146        let config = GcpCloudLoggingApiConfig::new(LogId::from_static("orders/checkout-v1.2_a"));
147
148        assert_eq!(
149            config.log_name("orders-prod"),
150            "projects/orders-prod/logs/orders%2Fcheckout-v1.2_a"
151        );
152    }
153}