Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backport everything up to November 2024 #3144

Merged
merged 21 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e4ee3a5
subscriber: fix flaky reload tests (#2798)
SpeedReach Nov 14, 2023
9883438
examples: suppress false positive clippy lint (#2846)
SUPERCILEX Jan 6, 2024
182420f
chore(ci): update actions/checkout action to v4 (#2845)
taiki-e Jan 6, 2024
a8ae276
journald: make level mappings configurable (#2824)
kaffarell Jan 11, 2024
4f08512
chore: Fix spelling (#2854)
jayvdb Jan 15, 2024
a46974d
docs: fix typo "synchonous" => "synchronous" (#2850)
mindeng Jan 20, 2024
c4aed1d
docs: Update README.md with correct link to tracing-etw (#2861)
cijothomas Jan 25, 2024
ce5b644
use const `thread_local`s when possible (#2838)
SUPERCILEX Jan 25, 2024
92633c8
macros: Fix missing field prefixes (#2878)
Turbo87 Feb 15, 2024
83136ef
macros: Fix non-simple macro usage without message (#2879)
Turbo87 Feb 16, 2024
7bb5bb2
tracing: fix event macros with constant field names in the first posi…
mladedav Mar 1, 2024
93f430c
tracing: allow `&[u8]` to be recorded as event/span field (#2954)
mladedav May 3, 2024
e9d3468
subscriber: add `set_span_events` to `fmt::Subscriber` (#2962)
lpraneis May 25, 2024
d921d5f
tracing-attributes: support const values for `target` and `name` (#2941)
dpc May 25, 2024
59a48c7
docs: remove non-existing method in comments (#2894)
kaffarell May 25, 2024
f3d83a1
macros: allow field path segments to be keywords (#2925)
svix-jplatte Jul 5, 2024
322c7e4
fix: prefix macro calls with ::core to avoid clashing with local macr…
joshka Jul 24, 2024
c15bff6
fix: correct SerializeField definition and doc formatting (#3040)
hds Jul 29, 2024
9210501
Add `json-subscriber` to ecosystem (#3121)
mladedav Oct 30, 2024
b6cb99e
tracing: add index API for `Field` (#2820)
Rustin170506 Nov 18, 2024
5294a84
subscriber: set `log` max level when reloading (#1270)
hawkw Feb 26, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/audit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
security_audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: actions-rs/audit-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
if: github.repository_owner == 'tokio-rs'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: taiki-e/create-gh-release-action@v1
with:
prefix: tracing(-[a-z]+)?
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ please let us know!)
[Tracy]: https://github.com/wolfpld/tracy
[`tracing-elastic-apm`]: https://crates.io/crates/tracing-elastic-apm
[Elastic APM]: https://www.elastic.co/apm
[`tracing-etw`]: https://github.com/microsoft/tracing-etw
[`tracing-etw`]: https://github.com/microsoft/rust_win_etw/tree/main/win_etw_tracing
[ETW]: https://docs.microsoft.com/en-us/windows/win32/etw/about-event-tracing
[`sentry-tracing`]: https://crates.io/crates/sentry-tracing
[Sentry]: https://sentry.io/welcome/
Expand Down
3 changes: 2 additions & 1 deletion examples/examples/sloggish/sloggish_subscriber.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub struct CurrentSpanPerThread {
impl CurrentSpanPerThread {
pub fn new() -> Self {
thread_local! {
static CURRENT: RefCell<Vec<Id>> = const { RefCell::new(vec![]) };
static CURRENT: RefCell<Vec<Id>> = const { RefCell::new(Vec::new()) };
};
Self { current: &CURRENT }
}
Expand Down Expand Up @@ -239,6 +239,7 @@ impl Subscriber for SloggishSubscriber {
self.print_indent(&mut stderr, indent).unwrap();
stack.push(span_id.clone());
if let Some(data) = data {
#[allow(clippy::map_identity)] // TODO remove in Rust 1.77
self.print_kvs(&mut stderr, data.kvs.iter().map(|(k, v)| (k, v)), "")
.unwrap();
}
Expand Down
32 changes: 29 additions & 3 deletions tracing-attributes/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ pub(crate) struct EventArgs {
#[derive(Clone, Default, Debug)]
pub(crate) struct InstrumentArgs {
level: Option<Level>,
pub(crate) name: Option<LitStr>,
target: Option<LitStr>,
pub(crate) name: Option<LitStrOrIdent>,
target: Option<LitStrOrIdent>,
pub(crate) parent: Option<Expr>,
pub(crate) follows_from: Option<Expr>,
pub(crate) skips: HashSet<Ident>,
Expand Down Expand Up @@ -87,6 +87,8 @@ impl Parse for InstrumentArgs {
// XXX: apparently we support names as either named args with an
// sign, _or_ as unnamed string literals. That's weird, but
// changing it is apparently breaking.
// This also means that when using idents for name, it must be via
// a named arg, i.e. `#[instrument(name = SOME_IDENT)]`.
if args.name.is_some() {
return Err(input.error("expected only a single `name` argument"));
}
Expand Down Expand Up @@ -211,8 +213,32 @@ impl Parse for EventArgs {
}
}

#[derive(Debug, Clone)]
pub(super) enum LitStrOrIdent {
LitStr(LitStr),
Ident(Ident),
}

impl ToTokens for LitStrOrIdent {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
LitStrOrIdent::LitStr(target) => target.to_tokens(tokens),
LitStrOrIdent::Ident(ident) => ident.to_tokens(tokens),
}
}
}

impl Parse for LitStrOrIdent {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
input
.parse::<LitStr>()
.map(LitStrOrIdent::LitStr)
.or_else(|_| input.parse::<Ident>().map(LitStrOrIdent::Ident))
}
}

struct StrArg<T> {
value: LitStr,
value: LitStrOrIdent,
_p: std::marker::PhantomData<T>,
}

Expand Down
13 changes: 13 additions & 0 deletions tracing-attributes/tests/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ fn fn_string(s: String) {
let _ = s;
}

#[instrument(fields(keywords.impl.type.fn = _arg), skip(_arg))]
fn fn_keyword_ident_in_field(_arg: &str) {}

#[derive(Debug)]
struct HasField {
my_field: &'static str,
Expand Down Expand Up @@ -146,6 +149,16 @@ fn string_field() {
});
}

#[test]
fn keyword_ident_in_field_name() {
let span = expect::span().with_fields(
expect::field("keywords.impl.type.fn")
.with_value(&"test")
.only(),
);
run_test(span, || fn_keyword_ident_in_field("test"));
}

fn run_test<F: FnOnce() -> T, T>(span: NewSpan, fun: F) {
let (subscriber, handle) = subscriber::mock()
.new_span(span)
Expand Down
72 changes: 72 additions & 0 deletions tracing-attributes/tests/instrument.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,75 @@ fn impl_trait_return_type() {

handle.assert_finished();
}

#[test]
fn name_ident() {
const MY_NAME: &str = "my_name";
#[instrument(name = MY_NAME)]
fn name() {}

let span_name = expect::span().named(MY_NAME);

let (subscriber, handle) = subscriber::mock()
.new_span(span_name.clone())
.enter(span_name.clone())
.exit(span_name.clone())
.drop_span(span_name)
.only()
.run_with_handle();

with_default(subscriber, || {
name();
});

handle.assert_finished();
}

#[test]
fn target_ident() {
const MY_TARGET: &str = "my_target";

#[instrument(target = MY_TARGET)]
fn target() {}

let span_target = expect::span().named("target").with_target(MY_TARGET);

let (subscriber, handle) = subscriber::mock()
.new_span(span_target.clone())
.enter(span_target.clone())
.exit(span_target.clone())
.drop_span(span_target)
.only()
.run_with_handle();

with_default(subscriber, || {
target();
});

handle.assert_finished();
}

#[test]
fn target_name_ident() {
const MY_NAME: &str = "my_name";
const MY_TARGET: &str = "my_target";

#[instrument(target = MY_TARGET, name = MY_NAME)]
fn name_target() {}

let span_name_target = expect::span().named(MY_NAME).with_target(MY_TARGET);

let (subscriber, handle) = subscriber::mock()
.new_span(span_name_target.clone())
.enter(span_name_target.clone())
.exit(span_name_target.clone())
.drop_span(span_name_target)
.only()
.run_with_handle();

with_default(subscriber, || {
name_target();
});

handle.assert_finished();
}
10 changes: 6 additions & 4 deletions tracing-core/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,10 +183,12 @@ enum Kind<T> {

#[cfg(feature = "std")]
thread_local! {
static CURRENT_STATE: State = const { State {
default: RefCell::new(None),
can_enter: Cell::new(true),
} };
static CURRENT_STATE: State = const {
State {
default: RefCell::new(None),
can_enter: Cell::new(true),
}
};
}

static EXISTS: AtomicBool = AtomicBool::new(false);
Expand Down
70 changes: 69 additions & 1 deletion tracing-core/src/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@
use crate::callsite;
use crate::stdlib::{
borrow::Borrow,
fmt,
fmt::{self, Write},
hash::{Hash, Hasher},
num,
ops::Range,
Expand Down Expand Up @@ -308,6 +308,11 @@ pub trait Visit {
self.record_debug(field, &value)
}

/// Visit a byte slice.
fn record_bytes(&mut self, field: &Field, value: &[u8]) {
self.record_debug(field, &HexBytes(value))
}

/// Records a type implementing `Error`.
///
/// <div class="example-wrap" style="display:inline-block">
Expand Down Expand Up @@ -380,6 +385,26 @@ where
t.as_value()
}

struct HexBytes<'a>(&'a [u8]);

impl<'a> fmt::Debug for HexBytes<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_char('[')?;

let mut bytes = self.0.iter();

if let Some(byte) = bytes.next() {
f.write_fmt(format_args!("{byte:02x}"))?;
}

for byte in bytes {
f.write_fmt(format_args!(" {byte:02x}"))?;
}

f.write_char(']')
}
}

// ===== impl Visit =====

impl<'a, 'b> Visit for fmt::DebugStruct<'a, 'b> {
Expand Down Expand Up @@ -540,6 +565,14 @@ impl Value for str {
}
}

impl crate::sealed::Sealed for [u8] {}

impl Value for [u8] {
fn record(&self, key: &Field, visitor: &mut dyn Visit) {
visitor.record_bytes(key, self)
}
}

#[cfg(feature = "std")]
impl crate::sealed::Sealed for dyn std::error::Error + 'static {}

Expand Down Expand Up @@ -771,6 +804,11 @@ impl Field {
pub fn name(&self) -> &'static str {
self.fields.names[self.i]
}

/// Returns the index of this field in its [`FieldSet`].
pub fn index(&self) -> usize {
self.i
}
}

impl fmt::Display for Field {
Expand Down Expand Up @@ -1141,6 +1179,17 @@ mod test {
assert!(valueset.is_empty());
}

#[test]
fn index_of_field_in_fieldset_is_correct() {
let fields = TEST_META_1.fields();
let foo = fields.field("foo").unwrap();
assert_eq!(foo.index(), 0);
let bar = fields.field("bar").unwrap();
assert_eq!(bar.index(), 1);
let baz = fields.field("baz").unwrap();
assert_eq!(baz.index(), 2);
}

#[test]
fn empty_value_set_is_empty() {
let fields = TEST_META_1.fields();
Expand Down Expand Up @@ -1249,4 +1298,23 @@ mod test {
});
assert_eq!(result, format!("{}", err));
}

#[test]
fn record_bytes() {
let fields = TEST_META_1.fields();
let first = &b"abc"[..];
let second: &[u8] = &[192, 255, 238];
let values = &[
(&fields.field("foo").unwrap(), Some(&first as &dyn Value)),
(&fields.field("bar").unwrap(), Some(&" " as &dyn Value)),
(&fields.field("baz").unwrap(), Some(&second as &dyn Value)),
];
let valueset = fields.value_set(values);
let mut result = String::new();
valueset.record(&mut |_: &Field, value: &dyn fmt::Debug| {
use core::fmt::Write;
write!(&mut result, "{:?}", value).unwrap();
});
assert_eq!(result, format!("{}", r#"[61 62 63]" "[c0 ff ee]"#));
}
}
14 changes: 11 additions & 3 deletions tracing-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,14 @@
#[cfg(not(feature = "std"))]
extern crate alloc;

#[doc(hidden)]
pub mod __macro_support {
// Re-export the `core` functions that are used in macros. This allows
// a crate to be named `core` and avoid name clashes.
// See here: https://github.com/tokio-rs/tracing/issues/2761
pub use core::{file, line, module_path, option::Option};
}

/// Statically constructs an [`Identifier`] for the provided [`Callsite`].
///
/// This may be used in contexts such as static initializers.
Expand Down Expand Up @@ -244,9 +252,9 @@ macro_rules! metadata {
$name,
$target,
$level,
::core::option::Option::Some(file!()),
::core::option::Option::Some(line!()),
::core::option::Option::Some(module_path!()),
$crate::__macro_support::Option::Some($crate::__macro_support::file!()),
$crate::__macro_support::Option::Some($crate::__macro_support::line!()),
$crate::__macro_support::Option::Some($crate::__macro_support::module_path!()),
$crate::field::FieldSet::new($fields, $crate::identify_callsite!($callsite)),
$kind,
)
Expand Down
2 changes: 1 addition & 1 deletion tracing-core/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ impl Kind {
pub const SPAN: Kind = Kind(Self::SPAN_BIT);

/// `enabled!` callsite. [`Subscriber`][`crate::subscriber::Subscriber`]s can assume
/// this `Kind` means they will never recieve a
/// this `Kind` means they will never receive a
/// full event with this [`Metadata`].
pub const HINT: Kind = Kind(Self::HINT_BIT);

Expand Down
2 changes: 1 addition & 1 deletion tracing-error/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Thanks to @CAD97 for contributing to this release!
- **TracedError**: `TracedError`, an error type wrapper that annotates an error
with the current span.
- **SpanTrace**:`SpanTrace::status` method and `SpanTraceStatus` type for
determing whether a `SpanTrace` was successfully captured (#614)
determining whether a `SpanTrace` was successfully captured (#614)

### Changed

Expand Down
4 changes: 2 additions & 2 deletions tracing-error/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ where
// erased `ErrorImpl` back to its original type, which is needed in order to forward our
// error/display/debug impls to the internal error type from the type erased error type.
//
// The repr(C) is necessary to ensure that the struct is layed out in the order we
// specified it so that we can safely access the vtable and spantrace fields thru a type
// The repr(C) is necessary to ensure that the struct is laid out in the order we
// specified it, so that we can safely access the vtable and spantrace fields through a type
// erased pointer to the original object.
let vtable = &ErrorVTable {
object_ref: object_ref::<E>,
Expand Down
Loading
Loading