use std::fmt;
use serde::{Deserialize, Deserializer, Serialize};
use time::format_description::well_known::Rfc3339;
use tracing_subscriber::{
EnvFilter,
fmt::{
self as tracing_fmt,
format::Writer,
time::{FormatTime, OffsetTime, UtcTime},
},
layer::SubscriberExt,
util::SubscriberInitExt,
};
use super::error::ObservabilityError;
const RUST_LOG_ENV: &str = "RUST_LOG";
const MAX_TRACE_CONTEXT_VALUE_LENGTH: usize = 128;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TracingConfig {
service_name: String,
json: bool,
env_filter: Option<String>,
time_zone: LogTimeZone,
}
impl TracingConfig {
#[must_use]
pub fn new(service_name: impl Into<String>) -> Self {
Self {
service_name: service_name.into().trim().to_owned(),
json: false,
env_filter: None,
time_zone: LogTimeZone::Utc,
}
}
pub fn try_new(service_name: impl Into<String>) -> Result<Self, ObservabilityError> {
let config = Self::new(service_name);
config.validate()?;
Ok(config)
}
#[must_use]
pub fn with_json(mut self, json: bool) -> Self {
self.json = json;
self
}
#[must_use]
pub fn with_env_filter(mut self, env_filter: impl Into<String>) -> Self {
self.env_filter = Some(env_filter.into().trim().to_owned());
self
}
#[must_use]
pub const fn with_time_zone(mut self, time_zone: LogTimeZone) -> Self {
self.time_zone = time_zone;
self
}
#[must_use]
pub fn service_name(&self) -> &str {
&self.service_name
}
#[must_use]
pub const fn json(&self) -> bool {
self.json
}
#[must_use]
pub fn env_filter(&self) -> Option<&str> {
self.env_filter.as_deref()
}
#[must_use]
pub const fn time_zone(&self) -> LogTimeZone {
self.time_zone
}
pub fn validate(&self) -> Result<(), ObservabilityError> {
validate_service_name(&self.service_name)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LogTimeZone {
#[default]
Utc,
Local,
}
impl LogTimeZone {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Utc => "utc",
Self::Local => "local",
}
}
}
#[derive(Debug, Clone)]
enum Rfc3339Timer {
Utc(UtcTime<Rfc3339>),
Local(OffsetTime<Rfc3339>),
}
impl Rfc3339Timer {
fn new(time_zone: LogTimeZone) -> Result<Self, ObservabilityError> {
match time_zone {
LogTimeZone::Utc => Ok(Self::Utc(UtcTime::rfc_3339())),
LogTimeZone::Local => Ok(Self::Local(
OffsetTime::local_rfc_3339().map_err(ObservabilityError::LocalTimeOffset)?,
)),
}
}
}
impl FormatTime for Rfc3339Timer {
fn format_time(&self, writer: &mut Writer<'_>) -> fmt::Result {
match self {
Self::Utc(timer) => timer.format_time(writer),
Self::Local(timer) => timer.format_time(writer),
}
}
}
pub fn init(service_name: &str, json: bool) -> Result<(), ObservabilityError> {
try_init(&TracingConfig::new(service_name).with_json(json))
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct TraceContext {
trace_id: Option<String>,
span_id: Option<String>,
request_id: Option<String>,
}
impl TraceContext {
#[must_use]
pub fn new(
trace_id: Option<String>,
span_id: Option<String>,
request_id: Option<String>,
) -> Self {
Self {
trace_id: normalize_trace_context_value(trace_id),
span_id: normalize_trace_context_value(span_id),
request_id: normalize_trace_context_value(request_id),
}
}
#[must_use]
pub fn trace_id(&self) -> Option<&str> {
self.trace_id.as_deref()
}
#[must_use]
pub fn span_id(&self) -> Option<&str> {
self.span_id.as_deref()
}
#[must_use]
pub fn request_id(&self) -> Option<&str> {
self.request_id.as_deref()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.trace_id.is_none() && self.span_id.is_none() && self.request_id.is_none()
}
}
impl<'de> Deserialize<'de> for TraceContext {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct TraceContextWire {
#[serde(default)]
trace_id: Option<String>,
#[serde(default)]
span_id: Option<String>,
#[serde(default)]
request_id: Option<String>,
}
let wire = TraceContextWire::deserialize(deserializer)?;
Ok(Self::new(wire.trace_id, wire.span_id, wire.request_id))
}
}
pub fn try_init(config: &TracingConfig) -> Result<(), ObservabilityError> {
config.validate()?;
let env_filter = env_filter(config)?;
let timer = Rfc3339Timer::new(config.time_zone)?;
if config.json {
tracing_subscriber::registry()
.with(env_filter)
.with(tracing_fmt::layer().with_timer(timer).json())
.try_init()?;
} else {
tracing_subscriber::registry()
.with(env_filter)
.with(tracing_fmt::layer().with_timer(timer))
.try_init()?;
}
Ok(())
}
fn env_filter(config: &TracingConfig) -> Result<EnvFilter, ObservabilityError> {
env_filter_from(config, std::env::var(RUST_LOG_ENV).ok())
}
pub(super) fn env_filter_from(
config: &TracingConfig,
env_value: Option<String>,
) -> Result<EnvFilter, ObservabilityError> {
config.validate()?;
if let Some(value) = env_value
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
{
return Ok(EnvFilter::try_new(value)?);
}
if let Some(value) = config
.env_filter
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
{
return Ok(EnvFilter::try_new(value)?);
}
Ok(EnvFilter::try_new("info,tower_http=info")?)
}
fn validate_service_name(value: &str) -> Result<(), ObservabilityError> {
if value.is_empty()
|| !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
{
return Err(ObservabilityError::InvalidServiceName);
}
Ok(())
}
fn normalize_trace_context_value(value: Option<String>) -> Option<String> {
let value = value?.trim().to_owned();
if value.is_empty()
|| value.len() > MAX_TRACE_CONTEXT_VALUE_LENGTH
|| !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
{
return None;
}
Some(value)
}