grow_apache_skywalking/logging/
client.rs1use 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#[derive(Debug, Clone, PartialEq)]
19pub enum LogEntry {
20 Record(LogRecord),
22 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#[async_trait]
52pub trait LogClient: Send + Sync {
53 fn send(&self, entry: LogEntry);
56 fn send_batch(&self, entries: Vec<LogEntry>) {
58 for e in entries {
59 self.send(e);
60 }
61 }
62 async fn flush(&self, timeout: Option<Duration>) -> Result<()>;
64 async fn close(&self) -> Result<()>;
66 fn stats(&self) -> BatchStats;
68 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#[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
96pub 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 pub fn batch_options(mut self, opts: BatchOptions) -> Self {
108 self.batch = opts;
109 self
110 }
111
112 pub fn resource(mut self, resource: Attributes) -> Self {
114 self.resource = resource;
115 self
116 }
117
118 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 pub fn redaction(mut self, redaction: Option<RedactionProcessor>) -> Self {
131 self.redaction = redaction;
132 self
133 }
134
135 pub fn min_severity(mut self, severity: Severity) -> Self {
137 self.min_severity = severity;
138 self
139 }
140
141 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 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 pub fn new(exporter: Arc<dyn LogExporter>) -> Result<Self> {
170 Self::builder(exporter).build()
171 }
172
173 pub fn processor(&self) -> &BatchProcessor {
175 &self.inner.processor
176 }
177
178 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 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#[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 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 pub fn with_min_severity(mut self, severity: Severity) -> Self {
289 self.min_severity = severity;
290 self
291 }
292
293 pub fn min_severity(&self) -> Severity {
295 self.min_severity
296 }
297
298 pub fn attributes(&self) -> &Attributes {
300 &self.attributes
301 }
302
303 pub fn enabled(&self, severity: Severity) -> bool {
305 severity >= self.min_severity
306 }
307
308 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 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 pub fn trace(&self, message: impl Into<String>, attributes: Attributes) {
332 self.log(Severity::Trace, message, attributes);
333 }
334 pub fn debug(&self, message: impl Into<String>, attributes: Attributes) {
336 self.log(Severity::Debug, message, attributes);
337 }
338 pub fn info(&self, message: impl Into<String>, attributes: Attributes) {
340 self.log(Severity::Info, message, attributes);
341 }
342 pub fn warn(&self, message: impl Into<String>, attributes: Attributes) {
344 self.log(Severity::Warn, message, attributes);
345 }
346 pub fn error(&self, message: impl Into<String>, attributes: Attributes) {
348 self.log(Severity::Error, message, attributes);
349 }
350 pub fn fatal(&self, message: impl Into<String>, attributes: Attributes) {
352 self.log(Severity::Fatal, message, attributes);
353 }
354}