use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use async_trait::async_trait;
use crate::core::transport::SDK_KEY;
use crate::core::Result;
use super::record::format_timestamp;
use super::{
active_trace_context, Attributes, BatchStats, DropCallback, LogClient, LogEntry, LogInput,
LogRecord, Logger, RedactionProcessor, Severity,
};
pub const LOG_SHIPPED_FIELD: &str = "log_shipped";
tokio::task_local! {
static REQUEST_ID: String;
}
pub async fn with_request_id<F: Future>(request_id: impl Into<String>, fut: F) -> F::Output {
REQUEST_ID.scope(request_id.into(), fut).await
}
pub fn current_request_id() -> Option<String> {
REQUEST_ID.try_with(Clone::clone).ok()
}
pub struct LogConnection {
pub logs: Arc<dyn LogClient>,
}
pub type LogConnector = Arc<
dyn Fn(&Attributes, &HashMap<String, String>, DropCallback) -> Result<Option<LogConnection>>
+ Send
+ Sync,
>;
pub type LineWriter = Arc<dyn Fn(&str) + Send + Sync>;
#[derive(Clone)]
pub struct InitOptions {
pub service: Option<String>,
pub level: Option<String>,
pub stdout: bool,
pub ship: Option<bool>,
pub env: Option<HashMap<String, String>>,
pub writer: Option<LineWriter>,
pub connector: Option<LogConnector>,
}
impl Default for InitOptions {
fn default() -> Self {
InitOptions {
service: None,
level: None,
stdout: true,
ship: None,
env: None,
writer: None,
connector: None,
}
}
}
impl fmt::Debug for InitOptions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("InitOptions")
.field("service", &self.service)
.field("level", &self.level)
.field("stdout", &self.stdout)
.field("ship", &self.ship)
.finish_non_exhaustive()
}
}
struct Tee {
writer: Option<LineWriter>,
logs: Option<Arc<dyn LogClient>>,
resource: Attributes,
service: String,
environment: Option<String>,
redaction: RedactionProcessor,
}
impl Tee {
fn line(&self, record: &LogRecord) -> String {
let mut line = serde_json::Map::new();
line.insert("time".into(), format_timestamp(record.timestamp).into());
line.insert("level".into(), record.severity.text().to_lowercase().into());
line.insert("msg".into(), record.body.clone().into());
line.insert("service".into(), self.service.clone().into());
if let Some(env) = &self.environment {
line.insert("environment".into(), env.clone().into());
}
if let (Some(t), Some(s)) = (&record.trace_id, &record.span_id) {
line.insert("trace_id".into(), t.clone().into());
line.insert("span_id".into(), s.clone().into());
}
for (k, v) in &record.attributes {
line.entry(k.clone()).or_insert_with(|| v.clone());
}
if self.logs.is_some() {
line.insert(LOG_SHIPPED_FIELD.into(), "sdk".into());
}
serde_json::Value::Object(line).to_string()
}
}
#[async_trait]
impl LogClient for Tee {
fn send(&self, entry: LogEntry) {
let LogEntry::Input(input) = entry else {
if let Some(logs) = &self.logs {
logs.send(entry);
}
return;
};
let severity = input.severity.unwrap_or_default();
let mut record = LogRecord::new(severity, input.message);
record.attributes = input.attributes;
if let Some(id) = current_request_id() {
record
.attributes
.entry("request_id".into())
.or_insert(id.into());
}
record.resource = self.resource.clone();
if let Some(ts) = input.timestamp {
record.timestamp = ts;
}
record.trace_id = input.trace_id;
record.span_id = input.span_id;
if record.trace_id.is_none() {
if let Some((trace, span, flags)) = active_trace_context() {
record.trace_id = Some(trace);
record.span_id = Some(span);
record.trace_flags = Some(flags);
}
}
if let Some(writer) = &self.writer {
writer(&self.line(&self.redaction.process(&record)));
}
if let Some(logs) = &self.logs {
logs.send(LogEntry::Record(record));
}
}
async fn flush(&self, timeout: Option<Duration>) -> Result<()> {
match &self.logs {
Some(logs) => logs.flush(timeout).await,
None => Ok(()),
}
}
async fn close(&self) -> Result<()> {
match &self.logs {
Some(logs) => logs.close().await,
None => Ok(()),
}
}
fn stats(&self) -> BatchStats {
self.logs.as_ref().map(|l| l.stats()).unwrap_or_default()
}
fn logger(&self, name: Option<&str>, attributes: Attributes) -> Logger {
let _ = name;
Logger::new(Arc::new(NoopClient), attributes)
}
}
struct NoopClient;
#[async_trait]
impl LogClient for NoopClient {
fn send(&self, _entry: LogEntry) {}
async fn flush(&self, _timeout: Option<Duration>) -> Result<()> {
Ok(())
}
async fn close(&self) -> Result<()> {
Ok(())
}
fn stats(&self) -> BatchStats {
BatchStats::default()
}
fn logger(&self, _name: Option<&str>, attributes: Attributes) -> Logger {
Logger::new(Arc::new(NoopClient), attributes)
}
}
#[derive(Clone)]
pub struct LoggingHandle {
tee: Arc<Tee>,
min: Severity,
closed: Arc<Mutex<bool>>,
}
impl fmt::Debug for LoggingHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LoggingHandle")
.field("service", &self.tee.service)
.field("shipped", &self.shipped())
.finish()
}
}
impl LoggingHandle {
pub fn logger(&self) -> Logger {
Logger::new(self.tee.clone(), Attributes::new()).with_min_severity(self.min)
}
pub fn client(&self) -> Arc<dyn LogClient> {
self.tee.clone()
}
pub fn shipped(&self) -> bool {
self.tee.logs.is_some()
}
pub fn service(&self) -> &str {
&self.tee.service
}
pub async fn flush(&self) -> Result<()> {
self.tee.flush(Some(Duration::from_secs(5))).await
}
pub async fn close(&self) -> Result<()> {
{
let mut closed = self.closed.lock().unwrap_or_else(|e| e.into_inner());
if *closed {
return Ok(());
}
*closed = true;
}
self.tee.close().await
}
pub async fn canary(&self, message: &str, attributes: Attributes) -> bool {
let Some(logs) = &self.tee.logs else {
return false;
};
let mut attrs = attributes;
attrs.insert("foundation.canary".into(), true.into());
logs.send(LogEntry::Input(
LogInput::new(message)
.severity(Severity::Info)
.attributes(attrs),
));
let _ = logs.flush(Some(Duration::from_secs(5))).await;
true
}
}
fn failed_line(record: &LogRecord) -> String {
let mut line = serde_json::Map::new();
line.insert("time".into(), format_timestamp(record.timestamp).into());
line.insert("level".into(), record.severity.text().to_lowercase().into());
line.insert("msg".into(), record.body.clone().into());
if let Some(v) = record.resource.get("service.name") {
line.insert("service".into(), v.clone());
}
if let Some(v) = record.resource.get("deployment.environment") {
line.insert("environment".into(), v.clone());
}
if let (Some(t), Some(s)) = (&record.trace_id, &record.span_id) {
line.insert("trace_id".into(), t.clone().into());
line.insert("span_id".into(), s.clone().into());
}
for (k, v) in &record.attributes {
line.entry(k.clone()).or_insert_with(|| v.clone());
}
line.insert(LOG_SHIPPED_FIELD.into(), "sdk_failed".into());
serde_json::Value::Object(line).to_string()
}
fn first(env: &HashMap<String, String>, names: &[&str]) -> Option<String> {
names
.iter()
.filter_map(|n| env.get(*n))
.map(|v| v.trim().to_string())
.find(|v| !v.is_empty())
}
pub fn init_logging(opts: InitOptions) -> LoggingHandle {
let env: HashMap<String, String> = opts
.env
.clone()
.unwrap_or_else(|| std::env::vars().collect());
let service = opts
.service
.clone()
.or_else(|| first(&env, &["GROW_SERVICE_NAME", "OTEL_SERVICE_NAME"]))
.unwrap_or_else(|| "unknown_service".into());
let environment = first(&env, &["GROW_ENVIRONMENT", "DEPLOYMENT_ENVIRONMENT"]);
let min = opts
.level
.clone()
.or_else(|| first(&env, &["LOG_LEVEL"]))
.and_then(|l| l.parse::<Severity>().ok())
.unwrap_or(Severity::Info);
let mut resource = Attributes::new();
resource.insert("service.name".into(), service.clone().into());
if let Some(e) = &environment {
resource.insert("deployment.environment".into(), e.clone().into());
}
let writer: LineWriter = opts
.writer
.clone()
.unwrap_or_else(|| Arc::new(|l: &str| println!("{l}")));
let ship = opts
.ship
.unwrap_or_else(|| first(&env, &["GROW_LOGGING_PROVIDER"]).as_deref() == Some(SDK_KEY));
let mut logs = None;
if ship {
let failed_writer = writer.clone();
let on_dropped: DropCallback = Arc::new(move |records, _reason| {
for record in records {
failed_writer(&failed_line(record));
}
});
let result = match &opts.connector {
Some(connect) => connect(&resource, &env, on_dropped),
None => connect_log_client(&resource, &env, on_dropped),
};
match result {
Ok(conn) => logs = conn.map(|c| c.logs),
Err(err) => writer(
&serde_json::json!({
"time": format_timestamp(std::time::SystemTime::now()),
"level": "warn",
"msg": format!("logging: {SDK_KEY} transport not available, stdout only ({:?})", err.code()),
"service": service,
})
.to_string(),
),
}
}
let tee = Tee {
writer: opts.stdout.then_some(writer),
logs,
resource,
service,
environment,
redaction: RedactionProcessor::default(),
};
LoggingHandle {
tee: Arc::new(tee),
min,
closed: Arc::new(Mutex::new(false)),
}
}
#[allow(unused_variables)]
pub fn connect_log_client(
resource: &Attributes,
env: &HashMap<String, String>,
on_dropped: DropCallback,
) -> Result<Option<LogConnection>> {
Ok(None)
}