tracing-subscriber: Switch to unconditional no_std

This commit is contained in:
Jonas Platte 2025-09-07 22:44:18 +02:00
parent 8738590fd1
commit c297a37096
22 changed files with 108 additions and 64 deletions

View File

@ -1,7 +1,6 @@
use crate::filter::level::{self, LevelFilter};
#[cfg(not(feature = "smallvec"))]
use alloc::vec;
#[cfg(not(feature = "std"))]
#[cfg(feature = "std")]
use alloc::boxed::Box;
use alloc::{string::String, vec::Vec};
use core::{cmp::Ordering, fmt, iter::FromIterator, slice, str::FromStr};
@ -126,7 +125,7 @@ impl<T> IntoIterator for DirectiveSet<T> {
#[cfg(feature = "smallvec")]
type IntoIter = smallvec::IntoIter<[T; 8]>;
#[cfg(not(feature = "smallvec"))]
type IntoIter = vec::IntoIter<T>;
type IntoIter = alloc::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.directives.into_iter()

View File

@ -3,7 +3,12 @@ use super::{
EnvFilter, FromEnvError,
};
use crate::sync::RwLock;
use std::env;
use alloc::{
format,
string::{String, ToString},
vec::Vec,
};
use std::{env, eprintln};
use thread_local::ThreadLocal;
use tracing::level_filters::STATIC_MAX_LEVEL;

View File

@ -4,6 +4,7 @@ use crate::filter::{
env::{field, FieldMap},
level::LevelFilter,
};
use alloc::{borrow::ToOwned, string::String, vec::Vec};
use std::{cmp::Ordering, fmt, iter::FromIterator, str::FromStr};
use tracing_core::{span, Level, Metadata};
@ -481,6 +482,7 @@ impl SpanMatcher {
#[cfg(test)]
mod test {
use super::*;
use alloc::{format, string::ToString, vec};
fn parse_directives(dirs: impl AsRef<str>) -> Vec<Directive> {
dirs.as_ref()

View File

@ -1,14 +1,17 @@
use matchers::Pattern;
use std::{
use alloc::{
borrow::ToOwned,
boxed::Box,
string::{String, ToString},
sync::Arc,
};
use core::{
cmp::Ordering,
error::Error,
fmt::{self, Write},
str::FromStr,
sync::{
atomic::{AtomicBool, Ordering::*},
Arc,
},
sync::atomic::{AtomicBool, Ordering::*},
};
use matchers::Pattern;
use std::error::Error;
use super::{FieldMap, LevelFilter};
use tracing_core::field::{Field, Visit};
@ -507,9 +510,7 @@ impl Visit for MatchVisitor<'_> {
Some((ValueMatch::NaN, ref matched)) if value.is_nan() => {
matched.store(true, Release);
}
Some((ValueMatch::F64(ref e), ref matched))
if (value - *e).abs() < f64::EPSILON =>
{
Some((ValueMatch::F64(ref e), ref matched)) if (value - *e).abs() < f64::EPSILON => {
matched.store(true, Release);
}
_ => {}
@ -576,6 +577,8 @@ impl Visit for MatchVisitor<'_> {
#[cfg(test)]
mod tests {
use super::*;
use alloc::format;
#[derive(Debug)]
#[allow(dead_code)]
struct MyStruct {

View File

@ -14,8 +14,10 @@ use crate::{
layer::{Context, Layer},
sync::RwLock,
};
use alloc::{fmt, str::FromStr, vec::Vec};
use core::cell::RefCell;
use directive::ParseError;
use std::{cell::RefCell, collections::HashMap, env, error::Error, fmt, str::FromStr};
use std::{collections::HashMap, env, error::Error};
use thread_local::ThreadLocal;
use tracing_core::{
callsite,
@ -835,6 +837,8 @@ impl Error for FromEnvError {
#[cfg(test)]
mod tests {
use super::*;
use alloc::format;
use std::println;
use tracing_core::field::FieldSet;
use tracing_core::*;

View File

@ -32,15 +32,14 @@ use crate::{
layer::{self, Context, Layer},
registry,
};
use std::{
use alloc::{boxed::Box, fmt, sync::Arc};
use core::{
any::TypeId,
cell::{Cell, RefCell},
fmt,
marker::PhantomData,
ops::Deref,
sync::Arc,
thread_local,
};
use std::thread_local;
use tracing_core::{
span,
subscriber::{Interest, Subscriber},

View File

@ -13,7 +13,6 @@ use crate::{
},
layer,
};
#[cfg(not(feature = "std"))]
use alloc::string::String;
use core::{
fmt,
@ -596,16 +595,17 @@ impl<'a> Iterator for Iter<'a> {
#[cfg(test)]
mod tests {
use super::*;
use alloc::{string::ToString, vec, vec::Vec};
#[cfg(feature = "std")]
use std::dbg;
feature! {
#![not(feature = "std")]
use alloc::{vec, vec::Vec, string::ToString};
// `dbg!` is only available with `libstd`; just nop it out when testing
// with alloc only.
macro_rules! dbg {
($x:expr) => { $x }
}
// `dbg!` is only available with `libstd`; just nop it out when testing
// with alloc only.
#[cfg(not(feature = "std"))]
macro_rules! dbg {
($x:expr) => {
$x
};
}
fn expect_parse(s: &str) -> Targets {
@ -775,6 +775,8 @@ mod tests {
// `println!` is only available with `libstd`.
#[cfg(feature = "std")]
fn size_of_filters() {
use std::println;
fn print_sz(s: &str) {
let filter = s.parse::<Targets>().expect("filter should parse");
println!(

View File

@ -4,10 +4,10 @@ use crate::{
layer::{self, Context},
registry::{self, LookupSpan, SpanRef},
};
use alloc::{fmt, format, string::String};
use core::{any::TypeId, marker::PhantomData, ops::Deref};
use format::{FmtSpan, TimingDisplay};
use std::{
any::TypeId, cell::RefCell, env, fmt, io, marker::PhantomData, ops::Deref, time::Instant,
};
use std::{cell::RefCell, env, eprintln, io, thread_local, time::Instant};
use tracing_core::{
field,
span::{Attributes, Current, Id, Record},
@ -1257,6 +1257,7 @@ mod test {
time,
};
use crate::Registry;
use alloc::{string::ToString, vec, vec::Vec};
use format::FmtSpan;
use regex::Regex;
use tracing::subscriber::with_default;
@ -1631,8 +1632,7 @@ mod test {
.with_timer(MockTime)
.with_span_events(FmtSpan::ACTIVE);
let (reloadable_layer, reload_handle) =
crate::reload::Layer::new(inner_layer);
let (reloadable_layer, reload_handle) = crate::reload::Layer::new(inner_layer);
let reload = reloadable_layer.with_subscriber(Registry::default());
with_default(reload, || {

View File

@ -7,12 +7,14 @@ use crate::{
},
registry::LookupSpan,
};
use serde::ser::{SerializeMap, Serializer as _};
use serde_json::Serializer;
use std::{
use alloc::{
collections::BTreeMap,
fmt::{self, Write},
format,
string::String,
};
use serde::ser::{SerializeMap, Serializer as _};
use serde_json::Serializer;
use tracing_core::{
field::{self, Field},
span::Record,

View File

@ -48,7 +48,6 @@ use tracing_log::NormalizeEvent;
#[cfg(feature = "ansi")]
use nu_ansi_term::{Color, Style};
mod escape;
use escape::Escape;
@ -433,6 +432,8 @@ impl<'writer> Writer<'writer> {
/// value implementing [`fmt::Write`] is a [`String`], it will contain
/// the formatted output of [`Format::format_event`], which may then be
/// used for other purposes.
///
/// [`String`]: alloc::string::String
#[must_use]
pub fn new(writer: &'writer mut impl fmt::Write) -> Self {
Self {
@ -1269,7 +1270,10 @@ impl field::Visit for DefaultVisitor<'_> {
),
)
} else {
self.record_debug(field, &format_args!("{}", Escape(&format_args!("{}", value))))
self.record_debug(
field,
&format_args!("{}", Escape(&format_args!("{}", value))),
)
}
}
@ -1294,7 +1298,7 @@ impl field::Visit for DefaultVisitor<'_> {
"message" => {
// Escape ANSI characters to prevent malicious patterns (e.g., terminal injection attacks)
write!(self.writer, "{:?}", Escape(value))
},
}
name if name.starts_with("r#") => write!(
self.writer,
"{}{}{:?}",
@ -1750,6 +1754,11 @@ impl Display for TimingDisplay {
#[cfg(test)]
pub(super) mod test {
use crate::fmt::{test::MockMakeWriter, time::FormatTime};
use alloc::{
borrow::ToOwned,
format,
string::{String, ToString},
};
use tracing::{
self,
dispatcher::{set_default, Dispatch},

View File

@ -189,7 +189,10 @@
//! https://docs.rs/tracing/latest/tracing/trait.Subscriber.html
//! [`tracing`]: https://crates.io/crates/tracing
//! [`fmt::format`]: mod@crate::fmt::format
use std::{any::TypeId, error::Error, io};
use alloc::boxed::Box;
use core::any::TypeId;
use std::{error::Error, io};
use tracing_core::{span, subscriber::Interest, Event, Metadata};
mod fmt_layer;
@ -1196,7 +1199,7 @@ pub fn try_init() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
#[cfg(not(feature = "env-filter"))]
let subscriber = {
use crate::{filter::Targets, layer::SubscriberExt};
use std::{env, str::FromStr};
use std::{env, eprintln, str::FromStr};
let targets = match env::var("RUST_LOG") {
Ok(var) => Targets::from_str(&var)
.map_err(|e| {
@ -1255,6 +1258,7 @@ mod test {
Subscriber,
},
};
use alloc::{borrow::ToOwned, string::String, vec::Vec};
use std::{
io,
sync::{Arc, Mutex, MutexGuard, TryLockError},

View File

@ -1,7 +1,7 @@
use crate::fmt::format::Writer;
use crate::fmt::time::FormatTime;
use std::sync::Arc;
use alloc::{format, string::String, sync::Arc};
/// Formats [local time]s and [UTC time]s with `FormatTime` implementations
/// that use the [`chrono` crate].
@ -108,8 +108,7 @@ impl FormatTime for ChronoUtc {
/// the supported syntax.
///
/// [`chrono::format::strftime`]: https://docs.rs/chrono/0.4.9/chrono/format/strftime/index.html
#[derive(Debug, Clone, Eq, PartialEq)]
#[derive(Default)]
#[derive(Debug, Clone, Eq, PartialEq, Default)]
enum ChronoFmtType {
/// Format according to the RFC 3339 convention.
#[default]
@ -118,13 +117,12 @@ enum ChronoFmtType {
Custom(String),
}
#[cfg(test)]
mod tests {
use crate::fmt::format::Writer;
use crate::fmt::time::FormatTime;
use std::sync::Arc;
use alloc::{borrow::ToOwned, string::String, sync::Arc};
use super::ChronoFmtType;
use super::ChronoLocal;

View File

@ -192,7 +192,6 @@
// permissive licensing, and of not having licensing issues being an
// obstacle to adoption, that text has been removed.
use std::fmt;
/// A date/time type which exists primarily to convert `SystemTime` timestamps into an ISO 8601
@ -333,7 +332,10 @@ impl From<std::time::SystemTime> for DateTime {
#[cfg(test)]
mod tests {
use i32;
use std::time::{Duration, UNIX_EPOCH};
use std::{
format,
time::{Duration, UNIX_EPOCH},
};
use super::*;

View File

@ -1,10 +1,13 @@
//! Abstractions for creating [`io::Write`] instances.
//!
//! [`io::Write`]: std::io::Write
use alloc::{boxed::Box, fmt, string::String, sync::Arc};
use std::{
fmt,
eprint,
io::{self, Write},
sync::{Arc, Mutex, MutexGuard},
print,
sync::{Mutex, MutexGuard},
};
use tracing_core::Metadata;
@ -715,9 +718,7 @@ impl TestWriter {
/// Returns a new `TestWriter` that writes to `stderr` instead of `stdout`.
pub fn with_stderr() -> Self {
Self {
use_stderr: true,
}
Self { use_stderr: true }
}
}
@ -1224,8 +1225,10 @@ mod test {
use crate::fmt::format::Format;
use crate::fmt::test::{MockMakeWriter, MockWriter};
use crate::fmt::Subscriber;
use alloc::vec::Vec;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::{dbg, format, println};
use tracing::{debug, error, info, trace, warn, Level};
use tracing_core::dispatcher::{self, Dispatch};

View File

@ -1675,7 +1675,6 @@ where
feature! {
#![any(feature = "std", feature = "alloc")]
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
macro_rules! layer_impl_body {
@ -1773,8 +1772,6 @@ feature! {
layer_impl_body! {}
}
impl<S, L> Layer<S> for Vec<L>
where
L: Layer<S>,

View File

@ -113,6 +113,8 @@ fn downcasts_to_layer() {
#[cfg(all(feature = "registry", feature = "std"))]
mod registry_tests {
use std::dbg;
use super::*;
use crate::registry::LookupSpan;

View File

@ -161,6 +161,8 @@
//! [`time` crate]: https://crates.io/crates/time
//! [`liballoc`]: https://doc.rust-lang.org/alloc/index.html
//! [`libstd`]: https://doc.rust-lang.org/std/index.html
#![no_std]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/tokio-rs/tracing/main/assets/logo-type.png",
issue_tracker_base_url = "https://github.com/tokio-rs/tracing/issues/"
@ -201,10 +203,11 @@
// future, reducing diff noise. Allow this even though clippy considers it
// "needless".
#![allow(clippy::needless_update)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[macro_use]
mod macros;

View File

@ -1,12 +1,12 @@
// taken from https://github.com/hyperium/http/blob/master/src/extensions.rs.
use crate::sync::{RwLockReadGuard, RwLockWriteGuard};
use std::{
use alloc::{boxed::Box, fmt};
use core::{
any::{Any, TypeId},
collections::HashMap,
fmt,
hash::{BuildHasherDefault, Hasher},
};
use std::collections::HashMap;
#[allow(warnings)]
type AnyMap = HashMap<TypeId, Box<dyn Any + Send + Sync>, BuildHasherDefault<IdHasher>>;

View File

@ -519,7 +519,10 @@ mod tests {
prelude::*,
registry::LookupSpan,
};
use std::sync::{Arc, Mutex};
use std::{
sync::{Arc, Mutex},
vec::Vec,
};
use tracing::{span, Subscriber};
#[test]

View File

@ -10,10 +10,11 @@ use crate::{
},
sync::RwLock,
};
use std::{
use core::{
cell::{self, Cell, RefCell},
sync::atomic::{fence, AtomicUsize, Ordering},
};
use std::thread_local;
use tracing_core::{
dispatcher::{self, Dispatch},
span::{self, Current, Id},
@ -536,7 +537,9 @@ mod tests {
use crate::{layer::Context, registry::LookupSpan, Layer};
use std::{
collections::HashMap,
dbg, println,
sync::{Arc, Mutex, Weak},
vec::Vec,
};
use tracing::{self, subscriber::with_default};
use tracing_core::{

View File

@ -1,3 +1,4 @@
use alloc::vec::Vec;
pub(crate) use tracing_core::span::Id;
#[derive(Debug)]

View File

@ -1,5 +1,8 @@
//! Extension traits and other utilities to make working with subscribers more
//! ergonomic.
#[cfg(feature = "std")]
use alloc::boxed::Box;
use core::fmt;
#[cfg(feature = "std")]
use std::error::Error;