use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use async_trait::async_trait;
use super::{
active_trace_context, AttrValue, Attributes, BatchOptions, BatchProcessor, BatchStats,
LogExporter, LogInput, LogRecord, RedactionProcessor, Severity,
};
use crate::core::Result;
#[derive(Debug, Clone, PartialEq)]
pub enum LogEntry {
Record(LogRecord),
Input(LogInput),
}
impl From<LogRecord> for LogEntry {
fn from(r: LogRecord) -> Self {
LogEntry::Record(r)
}
}
impl From<LogInput> for LogEntry {
fn from(i: LogInput) -> Self {
LogEntry::Input(i)
}
}
impl From<&str> for LogEntry {
fn from(message: &str) -> Self {
LogEntry::Input(LogInput::new(message))
}
}
impl From<String> for LogEntry {
fn from(message: String) -> Self {
LogEntry::Input(LogInput::new(message))
}
}
#[async_trait]
pub trait LogClient: Send + Sync {
fn send(&self, entry: LogEntry);
fn send_batch(&self, entries: Vec<LogEntry>) {
for e in entries {
self.send(e);
}
}
async fn flush(&self, timeout: Option<Duration>) -> Result<()>;
async fn close(&self) -> Result<()>;
fn stats(&self) -> BatchStats;
fn logger(&self, name: Option<&str>, attributes: Attributes) -> Logger;
}
struct Inner {
processor: BatchProcessor,
resource: Attributes,
redaction: Option<RedactionProcessor>,
min_severity: Severity,
closed: AtomicBool,
}
#[derive(Clone)]
pub struct BatchingLogClient {
inner: Arc<Inner>,
}
impl fmt::Debug for BatchingLogClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BatchingLogClient")
.field("resource", &self.inner.resource)
.field("stats", &self.stats())
.finish()
}
}
pub struct BatchingLogClientBuilder {
exporter: Arc<dyn LogExporter>,
batch: BatchOptions,
resource: Attributes,
redaction: Option<RedactionProcessor>,
min_severity: Severity,
}
impl BatchingLogClientBuilder {
pub fn batch_options(mut self, opts: BatchOptions) -> Self {
self.batch = opts;
self
}
pub fn resource(mut self, resource: Attributes) -> Self {
self.resource = resource;
self
}
pub fn resource_attribute(
mut self,
key: impl Into<String>,
value: impl Into<AttrValue>,
) -> Self {
self.resource.insert(key.into(), value.into());
self
}
pub fn redaction(mut self, redaction: Option<RedactionProcessor>) -> Self {
self.redaction = redaction;
self
}
pub fn min_severity(mut self, severity: Severity) -> Self {
self.min_severity = severity;
self
}
pub fn build(self) -> Result<BatchingLogClient> {
let processor = BatchProcessor::new(self.exporter, self.batch)?;
Ok(BatchingLogClient {
inner: Arc::new(Inner {
processor,
resource: self.resource,
redaction: self.redaction,
min_severity: self.min_severity,
closed: AtomicBool::new(false),
}),
})
}
}
impl BatchingLogClient {
pub fn builder(exporter: Arc<dyn LogExporter>) -> BatchingLogClientBuilder {
BatchingLogClientBuilder {
exporter,
batch: BatchOptions::default(),
resource: Attributes::new(),
redaction: Some(RedactionProcessor::default()),
min_severity: Severity::Info,
}
}
pub fn new(exporter: Arc<dyn LogExporter>) -> Result<Self> {
Self::builder(exporter).build()
}
pub fn processor(&self) -> &BatchProcessor {
&self.inner.processor
}
pub fn prepare(&self, entry: LogEntry) -> LogRecord {
let mut record = match entry {
LogEntry::Record(r) => r,
LogEntry::Input(i) => {
let severity = i.severity.unwrap_or_default();
let mut r = LogRecord {
timestamp: i.timestamp.unwrap_or_else(SystemTime::now),
observed_timestamp: Some(SystemTime::now()),
severity,
severity_text: severity.text().to_string(),
body: i.message,
attributes: i.attributes,
resource: Attributes::new(),
trace_id: i.trace_id,
span_id: i.span_id,
trace_flags: None,
};
if r.trace_id.is_none() {
if let Some((trace, span, flags)) = active_trace_context() {
r.trace_id = Some(trace);
r.span_id = Some(span);
r.trace_flags = Some(flags);
}
}
r
}
};
for (k, v) in &self.inner.resource {
record
.resource
.entry(k.clone())
.or_insert_with(|| v.clone());
}
if let Some(redaction) = &self.inner.redaction {
redaction.apply(&mut record);
}
record
}
pub async fn send_async(&self, entry: LogEntry) -> bool {
let record = self.prepare(entry);
self.inner.processor.add_async(record).await
}
}
#[async_trait]
impl LogClient for BatchingLogClient {
fn send(&self, entry: LogEntry) {
let record = self.prepare(entry);
self.inner.processor.add(record);
}
async fn flush(&self, timeout: Option<Duration>) -> Result<()> {
self.inner.processor.flush(timeout).await
}
async fn close(&self) -> Result<()> {
if self.inner.closed.swap(true, Ordering::SeqCst) {
return Ok(());
}
self.inner.processor.shutdown(None).await
}
fn stats(&self) -> BatchStats {
self.inner.processor.stats()
}
fn logger(&self, name: Option<&str>, attributes: Attributes) -> Logger {
let mut logger = Logger::new(Arc::new(self.clone()), attributes)
.with_min_severity(self.inner.min_severity);
if let Some(name) = name {
logger.attributes.insert("logger.name".into(), name.into());
}
logger
}
}
#[derive(Clone)]
pub struct Logger {
client: Arc<dyn LogClient>,
attributes: Attributes,
min_severity: Severity,
}
impl fmt::Debug for Logger {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Logger")
.field("attributes", &self.attributes)
.field("min_severity", &self.min_severity)
.finish()
}
}
impl Logger {
pub fn new(client: Arc<dyn LogClient>, attributes: Attributes) -> Self {
Logger {
client,
attributes,
min_severity: Severity::Info,
}
}
pub fn with_min_severity(mut self, severity: Severity) -> Self {
self.min_severity = severity;
self
}
pub fn min_severity(&self) -> Severity {
self.min_severity
}
pub fn attributes(&self) -> &Attributes {
&self.attributes
}
pub fn enabled(&self, severity: Severity) -> bool {
severity >= self.min_severity
}
pub fn child(&self, attributes: Attributes) -> Logger {
let mut merged = self.attributes.clone();
merged.extend(attributes);
Logger {
client: Arc::clone(&self.client),
attributes: merged,
min_severity: self.min_severity,
}
}
pub fn log(&self, severity: Severity, message: impl Into<String>, attributes: Attributes) {
if !self.enabled(severity) {
return;
}
let mut attrs = self.attributes.clone();
attrs.extend(attributes);
let input = LogInput::new(message).severity(severity).attributes(attrs);
self.client.send(LogEntry::Input(input));
}
pub fn trace(&self, message: impl Into<String>, attributes: Attributes) {
self.log(Severity::Trace, message, attributes);
}
pub fn debug(&self, message: impl Into<String>, attributes: Attributes) {
self.log(Severity::Debug, message, attributes);
}
pub fn info(&self, message: impl Into<String>, attributes: Attributes) {
self.log(Severity::Info, message, attributes);
}
pub fn warn(&self, message: impl Into<String>, attributes: Attributes) {
self.log(Severity::Warn, message, attributes);
}
pub fn error(&self, message: impl Into<String>, attributes: Attributes) {
self.log(Severity::Error, message, attributes);
}
pub fn fatal(&self, message: impl Into<String>, attributes: Attributes) {
self.log(Severity::Fatal, message, attributes);
}
}