mod event_data;
mod fatal;
mod human;
mod json;
mod layer;
mod panic_hook;
mod row;
mod span_context;
mod state;
#[cfg(test)]
mod tests;
mod timestamp;
pub(crate) use fatal::fatal;
use std::sync::Arc;
#[cfg(test)]
use std::sync::Mutex;
use time::OffsetDateTime;
use tokio::sync::broadcast;
use crate::telemetry::level::Level;
use crate::telemetry::logs_config::LogsConfig;
use crate::telemetry::service::Service;
use crate::telemetry::template::Template;
pub(crate) type Clock = Arc<dyn Fn() -> OffsetDateTime + Send + Sync>;
pub(crate) fn system_clock() -> Clock {
Arc::new(OffsetDateTime::now_utc)
}
pub(crate) const FATAL: &str = "fatal";
pub(crate) const CORRELATION_FIELD: &str = "correlation_id";
pub(crate) const TRACE_FIELD: &str = "trace_id";
pub(crate) const SPAN_FIELD: &str = "span_id";
pub(crate) enum Output {
Stdout,
#[cfg(test)]
Buffer(Arc<Mutex<Vec<u8>>>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogMessage {
timestamp: OffsetDateTime,
level: Level,
message: String,
correlation_id: Option<String>,
exception: Option<String>,
}
impl LogMessage {
pub fn timestamp(&self) -> OffsetDateTime {
self.timestamp
}
pub fn level(&self) -> Level {
self.level
}
pub fn message(&self) -> &str {
&self.message
}
pub fn correlation_id(&self) -> Option<&str> {
self.correlation_id.as_deref()
}
pub fn exception(&self) -> Option<&str> {
self.exception.as_deref()
}
}
pub struct Capture {
receiver: tokio::sync::broadcast::Receiver<LogMessage>,
min_level: Level,
}
impl Capture {
pub async fn next(&mut self) -> Option<LogMessage> {
loop {
match self.receiver.recv().await {
Ok(message) if message.level >= self.min_level => return Some(message),
Ok(_) => continue,
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => return None,
}
}
}
}
#[derive(Clone)]
pub struct Logging {
pub(crate) state: Arc<state::State>,
}
#[derive(Clone)]
pub(crate) struct Journal {
pub(crate) state: Arc<state::State>,
}
impl Journal {
pub(crate) fn new(config: LogsConfig, service: Service, output: Output, clock: Clock) -> Self {
Self {
state: Arc::new(state::State::new(&config, &service, output, clock)),
}
}
pub(crate) fn handle(&self) -> Logging {
Logging {
state: Arc::clone(&self.state),
}
}
}
impl Logging {
pub fn level(&self) -> Level {
self.state.level()
}
pub fn set_level(&self, level: Level) {
self.state.set_level(level);
}
pub fn template(&self) -> Template {
self.state.template()
}
pub fn set_template(&self, template: Template) {
self.state.set_template(template);
}
pub fn capture(&self, min_level: Level) -> Capture {
Capture {
receiver: self.state.subscribe(),
min_level,
}
}
}
pub(crate) fn set_panic_hook() {
panic_hook::install();
}