Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
27 changes: 25 additions & 2 deletions tracing-attributes/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,11 +268,26 @@ pub(crate) struct Fields(pub(crate) Punctuated<Field, Token![,]>);

#[derive(Clone, Debug)]
pub(crate) struct Field {
pub(crate) name: Punctuated<Ident, Token![.]>,
pub(crate) name: FieldName,
pub(crate) value: Option<Expr>,
pub(crate) kind: FieldKind,
}

#[derive(Clone, Debug)]
pub(crate) enum FieldName {
Str(LitStr),
Idents(Punctuated<Ident, Token![.]>),
}

impl ToTokens for FieldName {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
FieldName::Str(lit) => lit.to_tokens(tokens),
FieldName::Idents(idents) => idents.to_tokens(tokens),
}
}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum FieldKind {
Debug,
Expand Down Expand Up @@ -306,7 +321,15 @@ impl Parse for Field {
input.parse::<Token![?]>()?;
kind = FieldKind::Debug;
};
let name = Punctuated::parse_separated_nonempty_with(input, Ident::parse_any)?;
let name = if input.peek(syn::LitStr) {
FieldName::Str(input.parse::<LitStr>()?)
} else {
FieldName::Idents(Punctuated::parse_separated_nonempty_with(
input,
Ident::parse_any,
)?)
};

let value = if input.peek(Token![=]) {
input.parse::<Token![=]>()?;
if input.peek(Token![%]) {
Expand Down
10 changes: 7 additions & 3 deletions tracing-attributes/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use syn::{
Path, ReturnType, Signature, Stmt, Token, Type, TypePath,
};

use crate::attr::FieldName;
use crate::{
attr::{Field, Fields, FormatMode, InstrumentArgs, Level},
MaybeItemFn, MaybeItemFnRef,
Expand Down Expand Up @@ -189,9 +190,12 @@ fn gen_block<B: ToTokens>(
// If any parameters have the same name as a custom field, skip
// and allow them to be formatted by the custom field.
if let Some(ref fields) = args.fields {
fields.0.iter().all(|Field { ref name, .. }| {
let first = name.first();
first != name.last() || !first.iter().any(|name| name == &param)
fields.0.iter().all(|Field { ref name, .. }| match name {
FieldName::Idents(name) => {
let first = name.first();
first != name.last() || !first.iter().any(|name| name == &param)
}
FieldName::Str(lit) => *param == lit.value(),
})
} else {
true
Expand Down
10 changes: 10 additions & 0 deletions tracing-attributes/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,16 @@ mod expand;
/// }
/// ```
///
/// Keys can be passed as strings to 'fields', which can be useful for keys that are not valid Rust identifiers:
///
/// ```
/// # use tracing_attributes::instrument;
/// #[instrument(fields("my.type" = "foo"))]
/// fn my_function(arg: usize) {
/// // ...
/// }
/// ```
///
/// Adding the `ret` argument to `#[instrument]` will emit an event with the function's
/// return value when the function returns:
///
Expand Down
23 changes: 23 additions & 0 deletions tracing-attributes/tests/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ fn fn_string(s: String) {
let _ = s;
}

#[instrument(fields("trait.type" = val), skip(val))]
fn fn_string_key(val: i32) {}

#[instrument(fields(my_param = "From attribute"))]
fn fn_string_key_param(my_param: bool) {}

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

#[test]
fn string_key() {
let span = expect::span().with_fields(expect::field("trait.type").with_value(&42).only());
run_test(span, || {
fn_string_key(42);
});
}

#[test]
fn string_key_and_param() {
let span =
expect::span().with_fields(expect::field("my_param").with_value(&"From attribute").only());
run_test(span, || {
fn_string_key_param(true);
});
}

fn run_test<F: FnOnce() -> T, T>(span: NewSpan, fun: F) {
let (collector, handle) = collector::mock()
.new_span(span)
Expand Down