Skip to main content

grow_better_stack_logs/logging/
client.rs

1// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
2//! [`LogClient`], its batching implementation and the [`Logger`] facade.
3
4use std::fmt;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::Arc;
7use std::time::{Duration, SystemTime};
8
9use async_trait::async_trait;
10
11use super::{
12    active_trace_context, AttrValue, Attributes, BatchOptions, BatchProcessor, BatchStats,
13    LogExporter, LogInput, LogRecord, RedactionProcessor, Severity,
14};
15use crate::core::Result;
16
17/// Something a [`LogClient`] can send: a complete record or an input to fill in.
18#[derive(Debug, Clone, PartialEq)]
19pub enum LogEntry {
20    /// A complete record (only `resource` defaults and redaction are applied).
21    Record(LogRecord),
22    /// An input; timestamp, severity, resource and trace context are filled in.
23    Input(LogInput),
24}
25
26impl From<LogRecord> for LogEntry {
27    fn from(r: LogRecord) -> Self {
28        LogEntry::Record(r)
29    }
30}
31
32impl From<LogInput> for LogEntry {
33    fn from(i: LogInput) -> Self {
34        LogEntry::Input(i)
35    }
36}
37
38impl From<&str> for LogEntry {
39    fn from(message: &str) -> Self {
40        LogEntry::Input(LogInput::new(message))
41    }
42}
43
44impl From<String> for LogEntry {
45    fn from(message: String) -> Self {
46        LogEntry::Input(LogInput::new(message))
47    }
48}
49
50/// Client that ships logs to a service (SPEC §4 `LogClient`).
51#[async_trait]
52pub trait LogClient: Send + Sync {
53    /// Enqueues one record (applies redaction and defaults). Never blocks unless the batch
54    /// drop policy is `Block`.
55    fn send(&self, entry: LogEntry);
56    /// Enqueues several records.
57    fn send_batch(&self, entries: Vec<LogEntry>) {
58        for e in entries {
59            self.send(e);
60        }
61    }
62    /// Exports everything queued now.
63    async fn flush(&self, timeout: Option<Duration>) -> Result<()>;
64    /// Flushes and shuts down; idempotent.
65    async fn close(&self) -> Result<()>;
66    /// Batch counters.
67    fn stats(&self) -> BatchStats;
68    /// A [`Logger`] facade writing to this client; `name` becomes the `logger.name` attribute.
69    fn logger(&self, name: Option<&str>, attributes: Attributes) -> Logger;
70}
71
72struct Inner {
73    processor: BatchProcessor,
74    resource: Attributes,
75    redaction: Option<RedactionProcessor>,
76    min_severity: Severity,
77    closed: AtomicBool,
78}
79
80/// [`LogClient`] built from a [`LogExporter`], [`BatchOptions`], resource and redaction.
81/// Cheap to clone; clones share the queue.
82#[derive(Clone)]
83pub struct BatchingLogClient {
84    inner: Arc<Inner>,
85}
86
87impl fmt::Debug for BatchingLogClient {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.debug_struct("BatchingLogClient")
90            .field("resource", &self.inner.resource)
91            .field("stats", &self.stats())
92            .finish()
93    }
94}
95
96/// Builder for [`BatchingLogClient`].
97pub struct BatchingLogClientBuilder {
98    exporter: Arc<dyn LogExporter>,
99    batch: BatchOptions,
100    resource: Attributes,
101    redaction: Option<RedactionProcessor>,
102    min_severity: Severity,
103}
104
105impl BatchingLogClientBuilder {
106    /// Batch options (default [`BatchOptions::default`]).
107    pub fn batch_options(mut self, opts: BatchOptions) -> Self {
108        self.batch = opts;
109        self
110    }
111
112    /// Replaces the resource attributes added to every record.
113    pub fn resource(mut self, resource: Attributes) -> Self {
114        self.resource = resource;
115        self
116    }
117
118    /// Adds one resource attribute.
119    pub fn resource_attribute(
120        mut self,
121        key: impl Into<String>,
122        value: impl Into<AttrValue>,
123    ) -> Self {
124        self.resource.insert(key.into(), value.into());
125        self
126    }
127
128    /// Redaction applied to every record (default [`RedactionProcessor::default`]); `None`
129    /// disables redaction.
130    pub fn redaction(mut self, redaction: Option<RedactionProcessor>) -> Self {
131        self.redaction = redaction;
132        self
133    }
134
135    /// Default minimum severity for loggers from [`LogClient::logger`] (default `Info`).
136    pub fn min_severity(mut self, severity: Severity) -> Self {
137        self.min_severity = severity;
138        self
139    }
140
141    /// Starts the client; must be called inside a tokio runtime.
142    pub fn build(self) -> Result<BatchingLogClient> {
143        let processor = BatchProcessor::new(self.exporter, self.batch)?;
144        Ok(BatchingLogClient {
145            inner: Arc::new(Inner {
146                processor,
147                resource: self.resource,
148                redaction: self.redaction,
149                min_severity: self.min_severity,
150                closed: AtomicBool::new(false),
151            }),
152        })
153    }
154}
155
156impl BatchingLogClient {
157    /// Starts building a client around `exporter`.
158    pub fn builder(exporter: Arc<dyn LogExporter>) -> BatchingLogClientBuilder {
159        BatchingLogClientBuilder {
160            exporter,
161            batch: BatchOptions::default(),
162            resource: Attributes::new(),
163            redaction: Some(RedactionProcessor::default()),
164            min_severity: Severity::Info,
165        }
166    }
167
168    /// Client with default options.
169    pub fn new(exporter: Arc<dyn LogExporter>) -> Result<Self> {
170        Self::builder(exporter).build()
171    }
172
173    /// The underlying processor.
174    pub fn processor(&self) -> &BatchProcessor {
175        &self.inner.processor
176    }
177
178    /// Applies defaults, trace correlation and redaction, producing the record that is queued.
179    pub fn prepare(&self, entry: LogEntry) -> LogRecord {
180        let mut record = match entry {
181            LogEntry::Record(r) => r,
182            LogEntry::Input(i) => {
183                let severity = i.severity.unwrap_or_default();
184                let mut r = LogRecord {
185                    timestamp: i.timestamp.unwrap_or_else(SystemTime::now),
186                    observed_timestamp: Some(SystemTime::now()),
187                    severity,
188                    severity_text: severity.text().to_string(),
189                    body: i.message,
190                    attributes: i.attributes,
191                    resource: Attributes::new(),
192                    trace_id: i.trace_id,
193                    span_id: i.span_id,
194                    trace_flags: None,
195                };
196                if r.trace_id.is_none() {
197                    if let Some((trace, span, flags)) = active_trace_context() {
198                        r.trace_id = Some(trace);
199                        r.span_id = Some(span);
200                        r.trace_flags = Some(flags);
201                    }
202                }
203                r
204            }
205        };
206        for (k, v) in &self.inner.resource {
207            record
208                .resource
209                .entry(k.clone())
210                .or_insert_with(|| v.clone());
211        }
212        if let Some(redaction) = &self.inner.redaction {
213            redaction.apply(&mut record);
214        }
215        record
216    }
217
218    /// Sends and waits for room under the `Block` policy instead of blocking the thread.
219    pub async fn send_async(&self, entry: LogEntry) -> bool {
220        let record = self.prepare(entry);
221        self.inner.processor.add_async(record).await
222    }
223}
224
225#[async_trait]
226impl LogClient for BatchingLogClient {
227    fn send(&self, entry: LogEntry) {
228        let record = self.prepare(entry);
229        self.inner.processor.add(record);
230    }
231
232    async fn flush(&self, timeout: Option<Duration>) -> Result<()> {
233        self.inner.processor.flush(timeout).await
234    }
235
236    async fn close(&self) -> Result<()> {
237        if self.inner.closed.swap(true, Ordering::SeqCst) {
238            return Ok(());
239        }
240        self.inner.processor.shutdown(None).await
241    }
242
243    fn stats(&self) -> BatchStats {
244        self.inner.processor.stats()
245    }
246
247    fn logger(&self, name: Option<&str>, attributes: Attributes) -> Logger {
248        let mut logger = Logger::new(Arc::new(self.clone()), attributes)
249            .with_min_severity(self.inner.min_severity);
250        if let Some(name) = name {
251            logger.attributes.insert("logger.name".into(), name.into());
252        }
253        logger
254    }
255}
256
257/// Leveled logging facade over a [`LogClient`] (SPEC §4 `Logger`).
258///
259/// Records below the minimum severity (default `Info`) are discarded. When an OpenTelemetry
260/// span is active, its trace id, span id and flags are attached.
261#[derive(Clone)]
262pub struct Logger {
263    client: Arc<dyn LogClient>,
264    attributes: Attributes,
265    min_severity: Severity,
266}
267
268impl fmt::Debug for Logger {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        f.debug_struct("Logger")
271            .field("attributes", &self.attributes)
272            .field("min_severity", &self.min_severity)
273            .finish()
274    }
275}
276
277impl Logger {
278    /// Logger writing to `client` with base attributes.
279    pub fn new(client: Arc<dyn LogClient>, attributes: Attributes) -> Self {
280        Logger {
281            client,
282            attributes,
283            min_severity: Severity::Info,
284        }
285    }
286
287    /// Changes the minimum severity.
288    pub fn with_min_severity(mut self, severity: Severity) -> Self {
289        self.min_severity = severity;
290        self
291    }
292
293    /// Minimum severity in use.
294    pub fn min_severity(&self) -> Severity {
295        self.min_severity
296    }
297
298    /// Base attributes.
299    pub fn attributes(&self) -> &Attributes {
300        &self.attributes
301    }
302
303    /// Whether `severity` would be logged.
304    pub fn enabled(&self, severity: Severity) -> bool {
305        severity >= self.min_severity
306    }
307
308    /// A logger with extra base attributes (child attributes win).
309    pub fn child(&self, attributes: Attributes) -> Logger {
310        let mut merged = self.attributes.clone();
311        merged.extend(attributes);
312        Logger {
313            client: Arc::clone(&self.client),
314            attributes: merged,
315            min_severity: self.min_severity,
316        }
317    }
318
319    /// Logs at `severity`; call attributes override base attributes.
320    pub fn log(&self, severity: Severity, message: impl Into<String>, attributes: Attributes) {
321        if !self.enabled(severity) {
322            return;
323        }
324        let mut attrs = self.attributes.clone();
325        attrs.extend(attributes);
326        let input = LogInput::new(message).severity(severity).attributes(attrs);
327        self.client.send(LogEntry::Input(input));
328    }
329
330    /// Logs at `TRACE`.
331    pub fn trace(&self, message: impl Into<String>, attributes: Attributes) {
332        self.log(Severity::Trace, message, attributes);
333    }
334    /// Logs at `DEBUG`.
335    pub fn debug(&self, message: impl Into<String>, attributes: Attributes) {
336        self.log(Severity::Debug, message, attributes);
337    }
338    /// Logs at `INFO`.
339    pub fn info(&self, message: impl Into<String>, attributes: Attributes) {
340        self.log(Severity::Info, message, attributes);
341    }
342    /// Logs at `WARN`.
343    pub fn warn(&self, message: impl Into<String>, attributes: Attributes) {
344        self.log(Severity::Warn, message, attributes);
345    }
346    /// Logs at `ERROR`.
347    pub fn error(&self, message: impl Into<String>, attributes: Attributes) {
348        self.log(Severity::Error, message, attributes);
349    }
350    /// Logs at `FATAL`.
351    pub fn fatal(&self, message: impl Into<String>, attributes: Attributes) {
352        self.log(Severity::Fatal, message, attributes);
353    }
354}