use std::fmt;
use serde::{Deserialize, Deserializer, Serialize};
use time::format_description::well_known::Rfc3339;
use tracing::{Event, Subscriber, span::Record};
use tracing_subscriber::{
EnvFilter,
field::RecordFields,
fmt::{
self as tracing_fmt, FmtContext, FormattedFields,
format::{DefaultFields, FormatEvent, FormatFields, JsonFields, Writer},
time::{FormatTime, OffsetTime, UtcTime},
},
layer::SubscriberExt,
registry::LookupSpan,
util::SubscriberInitExt,
};
use super::error::ObservabilityError;
const RUST_LOG_ENV: &str = "RUST_LOG";
const MAX_TRACE_CONTEXT_VALUE_LENGTH: usize = 128;
pub const MAX_TRACING_SERVICE_NAME_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),
}
}
}
#[derive(Debug, Clone)]
struct ServiceNameTextFields {
service_name: String,
}
impl ServiceNameTextFields {
fn new(service_name: String) -> Self {
Self { service_name }
}
fn text_field(&self) -> String {
format!("service_name={:?}", self.service_name)
}
fn render_text<R: RecordFields>(&self, fields: R) -> Result<String, fmt::Error> {
let mut rendered = String::new();
DefaultFields::new().format_fields(Writer::new(&mut rendered), fields)?;
Ok(rendered)
}
fn update_text_fields(&self, current: &mut String, additional: &str) {
let configured = self.text_field();
if let Some(without_configured) = current.strip_suffix(&configured) {
*current = without_configured.trim_end().to_owned();
}
if !additional.is_empty() {
if !current.is_empty() {
current.push(' ');
}
current.push_str(additional);
}
if !current.is_empty() {
current.push(' ');
}
current.push_str(&configured);
}
}
impl<'writer> FormatFields<'writer> for ServiceNameTextFields {
fn format_fields<R: RecordFields>(
&self,
mut writer: Writer<'writer>,
fields: R,
) -> fmt::Result {
let mut rendered = self.render_text(fields)?;
self.update_text_fields(&mut rendered, "");
writer.write_str(&rendered)
}
fn add_fields(
&self,
current: &'writer mut FormattedFields<Self>,
fields: &Record<'_>,
) -> fmt::Result {
let rendered = self.render_text(fields)?;
self.update_text_fields(&mut current.fields, &rendered);
Ok(())
}
}
#[derive(Debug)]
struct JsonServiceEventFormat<F> {
inner: F,
service_name: String,
}
impl<F> JsonServiceEventFormat<F> {
fn new(inner: F, service_name: String) -> Self {
Self {
inner,
service_name,
}
}
fn insert_service_name(&self, value: &mut serde_json::Value) {
if let Some(fields) = value.as_object_mut() {
fields.insert("service_name".to_owned(), self.service_name.clone().into());
}
}
}
impl<S, N, F> FormatEvent<S, N> for JsonServiceEventFormat<F>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
N: for<'writer> FormatFields<'writer> + 'static,
F: FormatEvent<S, N>,
{
fn format_event(
&self,
context: &FmtContext<'_, S, N>,
mut writer: Writer<'_>,
event: &Event<'_>,
) -> fmt::Result {
let mut rendered = String::new();
self.inner
.format_event(context, Writer::new(&mut rendered), event)?;
let mut event: serde_json::Value =
serde_json::from_str(&rendered).map_err(|_| fmt::Error)?;
self.insert_service_name(&mut event);
if let Some(span) = event.get_mut("span") {
self.insert_service_name(span);
}
if let Some(spans) = event
.get_mut("spans")
.and_then(serde_json::Value::as_array_mut)
{
for span in spans {
self.insert_service_name(span);
}
}
writeln!(writer, "{event}")
}
}
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 {
let event_format = JsonServiceEventFormat::new(
tracing_fmt::format().with_timer(timer).json(),
config.service_name.clone(),
);
tracing_subscriber::registry()
.with(env_filter)
.with(
tracing_fmt::layer()
.event_format(event_format)
.fmt_fields(JsonFields::new()),
)
.try_init()?;
} else {
tracing_subscriber::registry()
.with(env_filter)
.with(
tracing_fmt::layer()
.with_timer(timer)
.fmt_fields(ServiceNameTextFields::new(config.service_name.clone())),
)
.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.len() > MAX_TRACING_SERVICE_NAME_LENGTH
|| !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)
}
#[cfg(test)]
mod tests {
use std::{
io,
sync::{Arc, Mutex},
};
use tracing_subscriber::{fmt::MakeWriter, layer::SubscriberExt};
use super::{JsonFields, JsonServiceEventFormat, ServiceNameTextFields, tracing_fmt};
#[derive(Clone, Default)]
struct Buffer(Arc<Mutex<Vec<u8>>>);
struct BufferWriter(Arc<Mutex<Vec<u8>>>);
impl io::Write for BufferWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.0
.lock()
.map_err(|_| io::Error::other("test output lock poisoned"))?
.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl<'writer> MakeWriter<'writer> for Buffer {
type Writer = BufferWriter;
fn make_writer(&'writer self) -> Self::Writer {
BufferWriter(Arc::clone(&self.0))
}
}
impl Buffer {
fn output(&self) -> String {
let bytes = self
.0
.lock()
.expect("test output lock should not be poisoned")
.clone();
String::from_utf8(bytes).expect("tracing output should be UTF-8")
}
}
fn emit_events() {
tracing::info!(event_field = 1, "outside span");
let span = tracing::info_span!("request", span_field = 2);
let _entered = span.enter();
tracing::info!(event_field = 3, "inside span");
}
#[test]
fn configured_service_name_is_present_on_text_events_and_spans() {
let output = Buffer::default();
let subscriber = tracing_subscriber::registry().with(
tracing_fmt::layer()
.without_time()
.with_ansi(false)
.with_target(false)
.with_writer(output.clone())
.fmt_fields(ServiceNameTextFields::new("example_service".to_owned())),
);
tracing::subscriber::with_default(subscriber, emit_events);
let lines = output
.output()
.lines()
.map(str::to_owned)
.collect::<Vec<_>>();
assert_eq!(lines.len(), 2);
assert!(
lines
.iter()
.all(|line| line.contains("service_name=\"example_service\""))
);
assert!(lines[1].matches("service_name=\"example_service\"").count() >= 2);
}
#[test]
fn configured_service_name_is_present_on_json_events_and_spans() {
let output = Buffer::default();
let event_format = JsonServiceEventFormat::new(
tracing_fmt::format().without_time().json(),
"example_service".to_owned(),
);
let subscriber = tracing_subscriber::registry().with(
tracing_fmt::layer()
.with_ansi(false)
.with_target(false)
.with_writer(output.clone())
.event_format(event_format)
.fmt_fields(JsonFields::new()),
);
tracing::subscriber::with_default(subscriber, emit_events);
let lines = output
.output()
.lines()
.map(str::to_owned)
.collect::<Vec<_>>();
assert_eq!(lines.len(), 2);
assert!(
lines
.iter()
.all(|line| line.contains(r#""service_name":"example_service""#))
);
assert!(
lines[1]
.matches(r#""service_name":"example_service""#)
.count()
>= 2
);
}
#[test]
fn json_span_updates_replace_fields_without_growing_the_buffer() {
use tracing_subscriber::{fmt::FormattedFields, registry::LookupSpan};
let output = Buffer::default();
let subscriber = tracing_subscriber::registry().with(
tracing_fmt::layer()
.with_writer(output.clone())
.event_format(JsonServiceEventFormat::new(
tracing_fmt::format().without_time().json(),
"configured_service".to_owned(),
))
.fmt_fields(JsonFields::new()),
);
let subscriber = Arc::new(subscriber);
tracing::subscriber::with_default(subscriber.clone(), || {
let parent = tracing::info_span!("parent", service_name = "incorrect");
let _parent = parent.enter();
let span = tracing::info_span!(
"child",
counter = 0,
service_name = "incorrect",
note = tracing::field::Empty
);
for counter in 1..=10_000 {
span.record("counter", counter);
}
span.record("note", "quoted\"\n中文");
span.record("service_name", "still_incorrect");
let stored = subscriber.span(&span.id().unwrap()).unwrap();
let extensions = stored.extensions();
let fields = &extensions
.get::<FormattedFields<JsonFields>>()
.unwrap()
.fields;
assert!(
fields.len() < 150,
"span fields must hold only current values"
);
assert_eq!(fields.matches("\"counter\"").count(), 1);
drop(extensions);
let _entered = span.enter();
tracing::info!("updated");
});
let event: serde_json::Value = serde_json::from_str(&output.output()).unwrap();
assert_eq!(event["service_name"], "configured_service");
assert_eq!(event["span"]["counter"], 10_000);
assert_eq!(event["span"]["note"], "quoted\"\n中文");
assert_eq!(event["span"]["service_name"], "configured_service");
assert!(
event["spans"]
.as_array()
.unwrap()
.iter()
.all(|span| span["service_name"] == "configured_service")
);
}
}