Escaping a Span Field Name in Instrument Attribute Macro

I'm working in an async context like so:

#[tracing::instrument]
pub async fn do_get() -> Result<()> {
  todo!()
}

I need to add a field named span.type, but if I attempt to do this, compilation fails because type is a reserved keyword:

#[tracing::instrument(fields(span.type))]
pub async fn do_get() -> Result<()> {
  todo!()
}

The above fails to compile due to type being reserved.

Is there a way to allow span.type as a field on the span?

The doc only says:

The name of the field must be a single valid Rust identifier, nested (dotted) field names are not supported.

In Rust a there is a valid way to specify a field named "type": r#type

Whether that works with the tracing macros, I don't know, but it may be worth trying. I don't see anything specific about it in the doc.

Of course, this may not be what you want if the name appears in tracing as r#type instead of type.

1 Like

Using r#type actually serializes "r#type" IIRC. We also ran into this bug (Rust keywords being forbidden in field paths inside instrument and other tracing macros) at my workplace a few months ago and I contributed a fix, which has been merged but not yet included in a release AFAIK.

4 Likes

Yes, as @jplatte mentions in his comment, if you try span.r#type or r#type, the literal value r#type is the attribute name.

Thank you! I'll subscribe to keep up-to-date on when it releases, thanks for putting the work in!

1 Like