115 Commits

Author SHA1 Message Date
Eliza Weisman
b740179fc6
attributes: suppress dead code warnings for compile tests (#2322)
The `async_fn` test file in `tracing-attributes` contains several
functions that exist just to test whether they _compile_, rather than
make assertions about their behavior. Because these functions are never
called, they (naturally) emit dead code warnings.

This commit adds `#[allow(dead_code)]` to the compilation tests, plus a
comment explaining why we do this.
2022-09-24 14:11:56 -07:00
Eliza Weisman
640cd3f390
attributes: update trybuild output for Rust 1.64.0 (#2322)
The error messages for these tests appear to have changed a bit with
Rust 1.64. This commit includes changes to the `.stderr` file after
running the tests with `TRYBUILD=overwrite`, in order to update the
expected output for the latest Rust.
2022-09-24 14:11:12 -07:00
Michael Goulet
760170bdaf attributes: add fake return to improve span on type error (#2270)
## Motivation

Return type errors on instrumented async functions are a bit vague,
since the type error originates within the macro itself due to the
indirection of additional `async {}` blocks generated in the proc-macro
(and due to the way that inference propagates around in Rust).

This leads to a pretty difficult to understand error. For example:

```rust
#[instrument]
async fn foo() -> String {
  ""
}
```

results in...

```
error[E0308]: mismatched types
 --> src/main.rs:1:1
  |
1 | #[tracing::instrument]
  | ^^^^^^^^^^^^^^^^^^^^^^- help: try using a conversion method: `.to_string()`
  | |
  | expected struct `String`, found `&str`
```

## Solution

Installs a fake `return` statement as the first thing that happens in
the auto-generated block of an instrumented async function.

This causes the coercion machinery within rustc to infer the right
return type (matching the the outer function) eagerly, as opposed to
after the `async {}` block has been type-checked.

This will cause us to both be able to point out the return type span
correctly, and properly suggest fixes on the expressions that cause the
type mismatch.

After this change, the example code above compiles to:

```
error[E0308]: mismatched types
  --> src/main.rs:3:5
   |
3  |     ""
   |     ^^- help: try using a conversion method: `.to_string()`
   |     |
   |     expected struct `String`, found `&str`
   |
note: return type inferred to be `String` here
  --> src/main.rs:2:20
   |
2  | async fn foo() -> String {
   |                   ^^^^^^
```
2022-09-19 11:47:54 -07:00
Eliza Weisman
3a193f3d30
chore: fix clippy::borrow_deref_ref warnings
This fixes some relatively recent clippy lints.
2022-09-16 13:15:39 -07:00
Christopher Durham
a3868af664
chore: fix minimal-versions correctness (#2246)
## Motivation

Fix minimal-versions failure.

## Solution

Upgrade all the dependencies to their most recent semver-compatible
version, adjusting back down as necessary for MSRV.

Essentially a cherry-pick of #2231, but redone by hand.

## Tests

- `cargo minimal-versions msrv verify -- cargo check --all-features`
- `cargo minimal-versions msrv verify -- cargo check --no-default-features`

## Methodology

- `cargo update && cargo upgrade --to-lockfile`
  - Identify [a bug](https://github.com/killercup/cargo-edit/issues/750) and manually resolve it
- loop; upgrade transitive deps
  - `cargo minimal-versions check --all-features`
  - Identify failing dep
  - `cargo minimal-versions tree -i dep --all-features`
  - Find the closest dependency leading to pulling in `dep`
  - `cargo add fixdep --optional` to force a more recent more-minimal-versions-correct version
- loop; downgrade to msrv
  - `cargo minimal-versions msrv verify -- cargo check --all-features`
  - Identify failing dep
  - `cargo minimal-versions tree -i dep --all-features`
  - Find the version that supports MSRV from lib.rs
  - `cargo upgrade dep@msrv`
2022-07-26 15:27:58 -07:00
Eliza Weisman
9c4bd43199
attributes: prepare to release v0.1.22 (#2203)
# 0.1.22 (July 1, 2022)

This release fixes an issue where using the `err` or `ret` arguments to
`#[instrument]` along with an overridden target, such as

```rust
#[instrument(target = "...", err, ret)]
```

would not propagate the overridden target to the events generated for
errors/return values.

### Fixed

- Error and return value events generated by `#[instrument(err)]` or
  `#[instrument(ret)]` not inheriting an overridden target (#2184)
- Incorrect default level in documentation (#2119)

Thanks to new contributor @tbraun96 for contributing to this release!
2022-07-01 11:15:48 -07:00
Thomas Braun
4a3f2991bf attributes: ensure res and err events inherit target (#2184)
## Motivation

Currently, when an `#[instrument]` attribute has an overridden target,
the events generated by `ret` and `err` arguments do not inherit that
target.

For example, if I write

```rust
#[tracing::instrument(target = "some_target", ret)
fn do_stuff() -> Something {
    // ...
}
```

the `do_stuff` span will have the target "some_target", but the return
value event generated by `ret` will have the current module path as its
target, and there is no way to change the return value event's target.

## Solution

This branch changes the macro expansion for `#[instrument]` with the
`ret` and/or `err` arguments so that an overridden target is propagated
to the events generated by `ret` and `err`.

Fixes #2183
2022-07-01 10:08:17 -07:00
Eliza Weisman
3ad7f99f64 core: impl field::Value for String (#2164)
## Motivation

Currently, it is rather difficult to record `String`s as field values,
even though `&str` is a primitive `Value` type. For example, this code
does not currently compile:

```rust
let my_string = String::from("hello world!");
tracing::debug!(my_string);
```

Instead, it is necessary to explicitly call `String::as_str` or a
similar conversion method:

```rust
let my_string = String::from("hello world!");
tracing::debug!(my_string = my_string.as_str());
```

This is unfortunate, as it makes a fairly straightforward, commomplace
task (recording a `String` as a field) unnecessarily verbose.

## Solution

This branch adds an `impl Value for String` in `tracing-core`. The impl
simply calls `String::as_str` and then calls `record_str`. Because
`Value` takes an `&self`, and there are preexisting `impl<T: Value>
Value` for `&T` and `&mut T`, the string is not consumed, and `&String`
or `&mut String`s can also be used as `Value`s.

I've also added tests validating that this actually works.
2022-06-22 15:01:24 -07:00
dependabot[bot]
586da9bc81 chore(deps): update tokio-test requirement from 0.2.0 to 0.3.0 (#1379)
Updates the requirements on [tokio-test](https://github.com/tokio-rs/tokio) to permit the latest version.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-0.2.0...tokio-0.3.0)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2022-06-07 10:01:02 -07:00
Eliza Weisman
db738eccb7
attributes: fix incorrect default level in docs (#2119)
This corrects contradictory information in the documentation --- in one
section, we state that the default level is `INFO` (which is correct),
but in the examples, we say it's `TRACE`, which is wrong. This commit
fixes that.

Fixes #2117

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2022-05-11 14:41:55 -07:00
Eliza Weisman
45c0a1099a
attributes: prepare to release v0.1.21 (#2097)
# 0.1.21 (April 26, 2022)

This release adds support for setting explicit parent and follows-from
spans in the `#[instrument]` attribute.

### Added

- `#[instrument(follows_from = ...)]` argument for setting one or more
  follows-from span ([#2093])
- `#[instrument(parent = ...)]` argument for overriding the generated
  span's parent ([#2091])

### Fixed

- Extra braces around `async` blocks in expanded code (causes a Clippy
  warning) ([#2090])
- Broken documentation links ([#2068], [#2077])

Thanks to @jarrodldavis, @ben0x539, and new contributor @jswrenn for
contributing to this release!

[#2093]: https://github.com/tokio-rs/tracing/pull/2093
[#2091]: https://github.com/tokio-rs/tracing/pull/2091
[#2090]: https://github.com/tokio-rs/tracing/pull/2090
[#2077]: https://github.com/tokio-rs/tracing/pull/2077
[#2068]: https://github.com/tokio-rs/tracing/pull/2068
2022-04-26 17:04:10 -07:00
Jack Wrenn
138a971829 attributes: permit #[instrument(follows_from = …)] (#2093)
This PR extends the `#[instrument]` attribute to accept an optional
`follows_from = …` argument that supplies any number of
`Span::follows_from` relationships to the generated `Span`.

## Motivation

This PR resolves #879.

## Solution

This PR largely follows the implementation strategy articulated by
@hawkw:
https://github.com/tokio-rs/tracing/issues/879#issuecomment-668168468

In that comment, @hawkw suggests taking one of two approaches:
1. each `follows_from` relationship is supplied with a distinct
   `follows_from` argument
2. the `follows_from` argument is provided once, and its value is a
   **list** of indirect causes

I take the second approach, since it is slightly more flexible: it
allows for the number of indirect causes to vary at runtime.

This addition is complemented by changes to `tracing-mock` to permit
making `follows_from` assertions for testing purposes.
2022-04-26 16:23:03 -07:00
Jack Wrenn
4c0e30fb32 attributes: permit setting parent span via #[instrument(parent = …)] (#2091)
This PR extends the `#[instrument]` attribute to accept an optionally
`parent = …` argument that provides an explicit parent to the generated
`Span`.

## Motivation

This PR resolves #2021 and partially resolves #879. (It only partly
resolves #879 in that it only provides a mechanism for specifying an
explicit parent, but *not* for invoking `follows_from`.)

## Solution

This PR follows the implementation strategy articulated by @hawkw:
https://github.com/tokio-rs/tracing/issues/879#issuecomment-668168468.
The user-provided value to the `parent` argument may be any expression,
and this expression is provided directly to the invocation of
[`span!`](https://tracing.rs/tracing/macro.span.html).
2022-04-26 16:23:03 -07:00
Jarrod Davis
0d13e5b419 attributes: remove extra braces around async blocks (#2090)
## Motivation

When using an `async` block (as an alternative to `async fn`, e.g. when
implementing a trait), `#[instrument]` adds extra braces around the
wrapped `async` block. This causes `rustc` to emit an `unused_braces`
lint in some cases (usually for single-line `async` blocks, as far as I
can tell). See #1831 for an example.

## Solution

Since the `async` block extracted by `AsyncInfo::from_fn` already has
braces around its statements, there's no need to wrap it with additional
braces. This updates `gen_block` to remove those extra braces when
generating the code providing the value of
`__tracing_instrument_future`.

- [x] add repros for `unused_braces` issue
- [x] remove extra braces from async blocks

Fixes #1831
2022-04-26 16:23:03 -07:00
Benjamin Herr
c8a2bb2d79
docs: more intra-doc links (#2077)
* docs: `cargo intraconv` for more intra-doc links

... also it deleted some redundant ones, and it got some things wrong,
and it was gonna delete some of the cross-crate docs.rs links we can't
do as intra-doc links so I passed `--no-favored`.

* docs: convert https:// links to std/core/alloc to intra-doc links

Note that this adds some more broken intra doc links when building
without std support, but that was already a thing and I expect people
who build their own docs without std support can handle it.

This time I gave up on sed and used ruby.

    find -name '*.rs' -exec ruby -i -p blah.rb {} +

with

    $_.gsub!(%r{
        https://doc\.rust-lang\.org/
        (?: stable/)?
        ((?:core | std | alloc)(?:/\S+?)*)
        /(\w+)\.(\w+)\.html}x
    ) {
      path, kind, name = $~.captures
      suffix = case kind
        when 'method' then '()'
        when 'macro' then '!'
        else ''
      end
      r = [path.gsub('/', '::'), '::', name, suffix].join
      STDERR.puts [path, kind, name, suffix, r].inspect
      r
    }
    $_.gsub!(%r{
        https://doc\.rust-lang\.org/
        (?: stable/)?
        ((?: core | std | alloc)(?:/\S+?)*)
        /(?:
          index\.html
          | $
          | (?= \#)
         )}x
    ) {
      path, _ = $~.captures
      r = path.gsub('/', '::')
      STDERR.puts [path, r].inspect
      r
    }

* docs: more cross-crate intra-doc links

cargo intraconv doesn't seem to get them reliably and also plenty of
links to other crates aren't actually intra-doc because they're in
crates that don't depend (or only dev-depend, or only conditionally
depend) on those crates, so this wasn't very automated.

I tried to only convert docs.rs links to unconditional dependencies to
intra-crate links, but it's possible that some slipped through in either
direction.
2022-04-19 18:11:09 +00:00
Benjamin Herr
438b013c01
docs: use intra-doc links instead of relative file paths (#2068)
## Motivation

#940, I guess. I kept running into the odd broken link in the docs and
eventually realized it's because a lot of stuff is reexported in parent
modules and so the file path based relative links couldn't possibly work
in all contexts. Looks like master already underwent this treatment but
I suspect this is easier than backporting.

## Solution

Intra-doc links seem pretty good.

I started with

```
        find -name \*.rs -exec sed -i -e '
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\.\./\w\+\.\(\w\+\)\.html@\1super::\2@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\.\./\(\w\+\)/\w\+\.\(\w\+\)\.html@\1super::\2::\3@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\.\./\.\./\w\+\.\(\w\+\)\.html@\1super::super::\2@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\.\./\.\./\(\w\+\)/\w\+\.\(\w\+\)\.html@\1super::super::\2::\3@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\.\./\(\w\+\)/index\.html@\1super::\2@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\.\./index\.html@\1super@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\.\./\(\w\+\)/\?$@\1super::\2@;
    
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\./\w\+\.\(\w\+\)\.html@\1self::\2@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\./\(\w\+\)/\w\+\.\(\w\+\)\.html@\1self::\2::\3@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\./\(\w\+\)/index\.html@\1self::\2@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\./index\.html@\1self@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\./\(\w\+\)/\?$@\1self::\2@;
    
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\w\+\.\(\w\+\)\.html@\1self::\2@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\(\w\+\)/\w\+\.\(\w\+\)\.html@\1self::\2::\3@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\(\w\+\)/index\.html@\1self::\2@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?index\.html@\1self@;
            s@\(//. \[[^]]*\]:\s\+\)[:"]\?\(\w\+\)/\?$@\1self::\2@;
    
            s@\(//. \[[^]]*\]:\s\+[A-Za-z_0-9:]\+\)#method\.\(\w\+\)@\1::\2@;
        ' {} +
```
and then removed redundant `self::`s when I realized you don't actually
need a `::` in the links, and fixed stuff up by hand as I ran into
errors from

```
x='--cfg docsrs --cfg tracing_unstable'; RUSTFLAGS=$x RUSTDOCFLAGS=$x cargo doc --all-features
```

I hope that's roughly how the docs are supposed to work.

I understand this is a relatively big unsolicited change in that it
touches a whole lot of files (definitely went further than I originally
intended), I'm happy to revise or split or reduce scope of this PR as
desired.
2022-04-14 12:12:43 -07:00
Christopher Durham
c1c75c9196 tests: put mocking functionality into a crate (#2009)
... instead of `#[path = ""]` importing it everywhere.

Make sure to use a diff review tool that understands file renaming 😅
(GitHub's diff view does.)

## Motivation

Transparency: I want to use the mocking functionality in the development
of a tracing component out-of-tree.

Additionally, this reduces the use of `#[path] mod` and file
multiple-inclusion, which aren't that great of a practice.

## Solution

The tracing test support module was already well self-contained, due to
being `#[path] mod` used in multiple places. As such, extracting it to
its own crate is rather mechanical, with no surprising blockers.

We additionally move the tracing-futures support module contents into
tracing_mock, for convenience. The one function which relies on
tokio-test is made optional.

It's a reasonable result for this functionality to stay unpublished, and
only used inside the repo, but pulling it out into a directly reusable
chunk instead of abusing the module system to reuse it via
multiple-inclusion is an improvement to code structure and
modularization.
2022-03-29 16:20:56 -07:00
Eliza Weisman
fda0aa4810
attributes: prepare to release v0.1.20 (#1976)
# 0.1.20 (March 8, 2022)

### Fixed

- Compilation failure with `--minimal-versions` due to a too-permissive
  `syn` dependency ([#1960])

### Changed

- Bumped minimum supported Rust version (MSRV) to 1.49.0 ([#1913])

Thanks to new contributor @udoprog for contributing to this release!

[#1960]: https://github.com/tokio-rs/tracing/pull/1960
[#1913]: https://github.com/tokio-rs/tracing/pull/1913
2022-03-08 14:48:07 -08:00
John-John Tedro
034139ea1e attributes: use correct minimal version of syn (#1960)
This sets the minimal version of `syn` to `1.0.43` - the actual minimal
version that is required to build `tracing-attributes`.

See this build failure in Tokio:
https://github.com/tokio-rs/tokio/runs/5344598894?check_suite_focus=true

CC: tokio-rs/tokio#4513
2022-03-08 14:14:38 -08:00
Eliza Weisman
32225276a9 chore: update MSRVs from 1.42 to 1.49 (#1913)
This updates all crates' MSRVs to 1.49 if they were not already greater
than that (`tracing-appender` is at 1.53). Rust 1.49+ is required to
update `parking_lot` to v0.12 (see #1878). Also, `futures-task` (which I
believe is only needed as a transitive dep) now needs 1.45+, so this
also fixes our CI build.

Because `tracing-opentelemetry` previously required 1.46.0, it had a
separate CI MSRV job. Since 1.49.0 is greater than 1.46.0, the separate
check for `tracing-opentelemetry` is no longer needed.

In the process, I removed deprecated uses of
`core::atomic::spin_loop_hint`, which is replaced with
`core::hint::spin_loop` in 1.49.
2022-02-07 15:39:26 -08:00
Eliza Weisman
46eda1ea37
attributes: prepare to release 0.1.19
# 0.1.19 (February 3, 2022)

This release introduces a new `#[instrument(ret)]` argument to emit an
event with the return value of an instrumented function.

### Added

- `#[instrument(ret)]` to record the return value of a function
  ([#1716])
- added `err(Debug)` argument to cause `#[instrument(err)]` to record
  errors with `Debug` rather than `Display ([#1631])

### Fixed

- incorrect code generation for functions returning async blocks
  ([#1866])
- incorrect diagnostics when using `rust-analyzer` ([#1634])

Thanks to @Swatinem, @hkmatsumoto, @cynecx, and @ciuncan for
contributing to this release!

[#1716]: https://github.com/tokio-rs/tracing/pull/1716
[#1631]: https://github.com/tokio-rs/tracing/pull/1631
[#1634]: https://github.com/tokio-rs/tracing/pull/1634
[#1866]: https://github.com/tokio-rs/tracing/pull/1866
2022-02-03 17:00:16 -08:00
Arpad Borsos
89471ab84b attributes: correctly instrument fns returning an async move block (#1866)
This should take care of half of #1863, meaning it should instrument
functions returning an unboxed `async move` block.

This unfortunately does not cover generic `impl Future` returns, such as
`std::future::ready()` and similar :-(
2022-02-03 16:10:18 -08:00
Hirochika Matsumoto
fedb87499a attributes: implement #[instrument(ret)] (#1716)
* attributes: implement `#[instrument(ret)]`

## Motivation

Currently, users have to explicitly call logging functions at the end of
functions if they wanted to record values being returned. For example,
```rust
fn increment(a: i32) -> i32 {
    let succ = a + 1;
    tracing::debug!(?succ);
    succ
}
```
The code above will be significantly simpler if we provide the
functionality to record returned values.

## Solution

This PR adds the exact feature we're talking here, which enables users
to write the code below instead.
```rust
#[instrument(ret)]
fn increment(a: i32) -> i32 {
    a + 1
}
```

Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2021-12-19 16:23:54 -08:00
Folyd
3a86d4810c chore: fix cargo MSRV field typo (#1742) 2021-11-23 13:50:24 -08:00
Eliza Weisman
e62e7165f4 chore: add MSRV cargo metadata (#1730)
This branch adds the `[package.rust]` metadata to `Cargo.toml` for all
crates. See https://rust-lang.github.io/rfcs/2495-min-rust-version.html
for details.
2021-11-19 16:57:37 -08:00
Eliza Weisman
f5aac47f68 attributes: refactor into separate modules (#1643)
## Motivation

Currently, `tracing-attributes` consists of one very large `lib.rs`
module that's 1358 lines long. In my opinion, this makes the code
somewhat hard to navigate.

## Solution

This branch refactors `tracing-attributes` so that most of the code is
split into two separate modules: `attrs.rs`, which contains the types
representing the attribute arguments and the code for parsing them, and
`expand.rs`, which contains the code for actually expanding an
`#[instrument]` macro to generate the instrumented code. For the most
part, this was a pretty clean split.

I also did a small change to the way `async-trait` support is
implemented; moving the two steps for generating instrumented code for
`async-trait` to two methods on the `AsyncTraitInfo` struct; one for
determining if the instrumented function is also an `async-trait` method
and finding the necessary information to instrument it, and one for
generating the instrumented code. This feels a bit neater than doing all
of that in the `gen_function` function.

There shouldn't be any functional changes or significant
implementatation changes (besides the `async-trait` change) in this
branch; just moving code around.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-10-22 13:26:09 -07:00
cynecx
8540abcb82 attributes: speculative expand when parsing fails (#1634)
## Motivation

Recent `rust-analyzer` versions enabled automatic expansion of proc
macro attributes by default. This is a problem with `#[instrument]`,
because it currently produces a `compile_error!` when parsing the code
inside the `#[instrument]`ed function fails, and *discards* those
tokens. This means that if the `#[instrument]` attribute is placed on a
function whose implementation fails to parse, recent versions of
`rust-analyzer` will no longer be able to display diagnostics for those
errors. In some cases, this can also break autocompletion.

## Solution

This branch changes `#[instrument]` to always expand to the tokens
contained in the `#[instrument]`ed function body, regardless of whether
or not they could be parsed successfully. Now, an error is only emitted
when the `#[instrument]` attribute *itself* could not be parsed. Since
the instrumented function is always expanded, any errors within that
function can be displayed properly by `rust-analyzer`.

Fixes #1633.
2021-10-22 13:26:09 -07:00
Ceyhun Can Ulker
f515e9d35c attributes: add err(Debug) meta to use Debug impl (#1631)
## Motivation

This PR attempts to solve #1630 by introducing `err(Debug)` meta to
`intrument` attribute macro. As `err` meta causes the error (`e`)
returned by instrumented function to be passed to `tracing::error!(error
= %e)` i.e. makes it use the `Display` implementation of `e`, the newly
added `err(Debug)` makes expands to `tracing::error!(error = ?e)` which
makes the `error!` macro to use `Debug` implementation for `e`. `err`
and `err(Debug)` are mutually exclusive, adding both will create a
compilation error.

`err(Display)` is also supported to specify `Display` explicitly.

As tried to describe, for some types implementing `Error` it might be
more suitable to use `Debug` implementation as in the case of
`eyre::Result`. This frees us to manually go over the error chain and
print them all, so that `instrument` attribute macro would do it for us.

## Solution

- Added a custom keyword `err(Debug)` similar to `err`,
- Add `err(Debug)` field to `InstrumentArgs`,
- Add parsing for `err(Debug)` arg and check for conflicts with `err`,
- Generate `tracing::error!(error = ?e)` when `err(Debug)` is `true` and
  `tracing::error!(error = %e)` when `err(Display)` or `err` is `true`,
- Interpolate generated `err_block` into `Err` branches in both async
  and sync return positions, if `err` or `err(Debug)` is `true`.
2021-10-22 13:26:09 -07:00
Eliza Weisman
645f282eee
attributes: prepare to release 0.1.18 (#1621)
# 0.1.18 (October 5, 2021)

This release fixes issues introduced in v0.1.17.

### Fixed

- fixed mismatched types compiler error that may occur when using
  `#[instrument]` on an `async fn` that returns an `impl Trait` value
  that includes a closure ([#1616])
- fixed false positives for `clippy::suspicious_else_formatting`
  warnings due to rust-lang/rust-clippy#7760 and
  rust-lang/rust-clippy#6249 ([#1617])
- fixed `clippy::let_unit_value` lints when using `#[instrument]`
  ([#1614])

[#1617]: https://github.com/tokio-rs/tracing/pull/1617
[#1616]: https://github.com/tokio-rs/tracing/pull/1616
[#1614]: https://github.com/tokio-rs/tracing/pull/1614
2021-10-05 14:10:42 -07:00
Eliza Weisman
7dda7f5e90 attributes: remove unnecessary quote_spanned! (#1617)
## Motivation

Apparently, using `quote_spanned!` can trigger a Clippy bug where the
text `else`, even inside a comment, _may_ cause the
`suspicious_else_formatting` lint to be triggered incorrectly (see
rust-lang/rust-clippy#7760 and rust-lang/rust-clippy#6249). This causes
the lint to fire in some cases when the `#[instrument]` attribute is
used on `async fn`s. See issue #1613 for details.

## Solution

It turns out that some of the uses of `quote_spanned!` in the
`tracing-attributes` code generation are not needed. We really only need
`quote_spanned!` when actually interpolating the user provided code into
a block, not in the `tracing-attributes` code that inserts the generated
code for producing the span etc. Replacing some of these
`quote_spanned!` uses with the normal `quote!` macro still generates
correct location diagnostics for errors in the user code, but fixes the
incorrect clippy lint.

I've added a few test cases that should reproduce the bug.

Fixes #1613

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-10-05 13:27:27 -07:00
Eliza Weisman
243a3e2d2f attributes: fix compile error with instrumented async functions (#1616)
## Motivation

The changes in #1607 introduced a potential compilation error when using
the `#[instrument]` attribute on `async fn`s that return a type that
includes a closure or is otherwise unnameable. This is because the
future's body code was quoted in two separate places in order to have a
separate branch when the span is statically disabled. This means that
when a closure is returned, it will technically have two distinct types
based on whether or not the span is enabled, since it originates from
two separate source code locations (although `quote_spanned!` obscures
this, so the compiler diagnostic will appear to have two closures
originating from the same location).

## Solution

This branch fixes this issue by changing the code generated for
`#[instrument]`ed async functions. Unfortunately, for async functions,
we can't have the optimization of not creating the span at all when the
level is disabled, because we need to create the span _before_ creating
the future, as it may borrow arguments.

I've also added tests reproducing issue #1615

Fixes #1615
2021-10-05 13:27:27 -07:00
Eliza Weisman
ac74ba0ca5 attributes: suppress clippy::suspicious_else without nop let (#1614)
Currently, `tracing-attributes` generates a `let _ = ();` in between the
`if tracing::level_enabled!(...) {}` and the function body. This is
intended to suppress the `clippy::suspicious_else_formatting` lint,
which is generated when an `if` is followed immediately by a block with
no whitespace in between. Since we can't add whitespace in the generated
code (as `quote` produces a stream of _rust tokens_, not text), we
can't suppress the lint without adding a no-op statement.

However, unfortunately, the no-op let triggers a _different_ lint
(`clippy::let_unit_value`), when `clippy::pedantic` is enabled. This is
kind of annoying for some users.

This branch changes the code to suppress the
`suspicious_else_formatting` lint using `#[allow(...)]` attributes,
instead. The warning is turned back on inside of user code, since users
probably want the warning.
2021-10-05 13:27:27 -07:00
Eliza Weisman
66cd79f72a
attributes: prepare to release v0.1.17 (#1611)
# 0.1.17 (October 1, 2021)

This release significantly improves performance when
`#[instrument]`-generated spans are below the maximum enabled level.

### Added

- improve performance when skipping `#[instrument]`-generated spans
  below the max level ([#1600], [#1605])

Thanks to @oli-obk for contributing to this release!

[#1600]: https://github.com/tokio-rs/tracing/pull/1600
[#1605]: https://github.com/tokio-rs/tracing/pull/1605
2021-10-01 16:58:39 -07:00
Eliza Weisman
c9db496a95 attributes: skip async spans if level disabled (#1607)
## Motivation

In #1600, the `instrument` code generation was changed to avoid ever
constructing a `Span` struct if the level is explicitly disabled.
However, for `async` functions, `#[instrument]` will currently still
create the span, but simply skips constructing an `Instrument` future if
the level is disabled.

## Solution

This branch changes the `#[instrument]` code generation for async blocks
to totally skip constructing the span if the level is disabled. I also
simplfied the code generation a bit by combining the shared code between
the `err` and non-`err` cases, reducing code duplication a bit.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-10-01 14:34:01 -07:00
Oli Scherer
3b038ed3ad
attributes: help LLVM understand that some spans are never going to do anything (#1600) (#1605)
## Motivation

Adding `#[instrument(level = "debug")]` attributes to functions in rustc
caused a performance regression (in release, where `debug!` is fully
optimized out) across all crates:
https://github.com/rust-lang/rust/pull/89048#issuecomment-929566530

While trying to debug this, I noticed that spans don't have the same
advantage that events have wrt to how LLVM sees them. Spans (or more
precisely, the enter-guard), will get dropped at the end of the scope,
which throws a spanner into the LLVM optimization pipeline. I am not
entirely sure where the problem is, but I am moderately certain that the
issue is that even entering a dummy span is too much code for LLVM to
reliably (or at all) optimize out.

## Solution

My hope is that in trusting the Rust compiler to generate cool code when using
drop flags, we can essentially generate a drop flag that depends on something we
know (due to events working as expected) to be optimizable.

So instead of doing

```rust
let _x = span!();
let _y = _x.enter();
// lotsa code
drop(_y)
```

we do

```rust
let _x;
let _y;
let must_drop = false;
if level_enabled!(DEBUG) {
    must_drop = true;
    _x = span!();
    _y = _x.enter();
}
// lotsa code
if must_drop {
    drop(_y)
}
```

I believe this will allow LLVM to properly optimize this again. Testing that
right now, but I wanted to open this PR immediately for review.
2021-10-01 09:51:02 -07:00
Eliza Weisman
47036aa61d
attributes: prepare to release v0.1.16 (#1560)
# 0.1.16 (September 13, 2021)

This release adds a new `#[instrument(skip_all)]` option to skip
recording *all* arguments to an instrumented function as fields.
Additionally, it adds support for recording arguments that are `tracing`
primitive types as typed values, rather than as `fmt::Debug`.

### Added

- add `skip_all` option to `#[instrument]` ([#1548])
- record primitive types as primitive values rather than as `fmt::Debug`
  ([#1378])
- added support for `f64`s as typed values ([#1522])

Thanks to @Folyd and @jsgf for contributing to this release!

[#1548]: https://github.com/tokio-rs/tracing/pull/1548
[#1378]: https://github.com/tokio-rs/tracing/pull/1378
[#1522]: https://github.com/tokio-rs/tracing/pull/1524
2021-09-13 11:41:06 -07:00
Jeremy Fitzhardinge
665170ddc3
attributes: add skip_all (#1548)
Using `#[instrument(skip_all)]` is equivalent to `#[instrument(skip(foo,
bar..))]` for all the parameters.
2021-09-12 09:57:21 -07:00
Folyd
b8b00929c8 attributes: record f32 and f64 as Value (#1522)
Companion PR with #1507.
2021-09-04 11:57:42 -07:00
Eliza Weisman
270de1cde0
docs: fix a bunch of RustDoc warnings/errors (#1524)
This branch fixes some minor RustDoc issues. In particular:

- The `broken_intra_doc_links` lint was renamed to
  `rustdoc::broken_intra_doc_links`. This generates a warning, since the
  old name was deprecated.
- `ignore` code blocks are specifically for _Rust_ code that should not
  be compiled, not for other text blocks. We were using `ignore` on JSON
  blocks, which generates a warning.
- A bunch of links in `tracing-subscriber`'s RustDocs were broken. This
  fixes that.

I also changed the Netlify configuration to run with `-D warnings`, so that
we can surface RustDoc warnings in CI builds.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-08-27 11:23:46 -07:00
Teo Klestrup Röijezon
5f0f5cc97e
chore: fix warnings introduced by Rustc 1.54 (#1495)
Split from #1460
2021-08-06 09:36:27 -07:00
Folyd
9c031d7b79 attributes: don't record primitive types of the function arguments as fmt::Debug (#1378)
The default behavior of `tracing::instrument` attribution will record
all of the function arguments as `fmt::Debug`, which is overwhelmed and
unnecessary for those primitive types, such as `bool`, `u8`, `i8`,
`u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `usize`, and `isize`. Another
concerning reason is that we‘ll lose the type info of those primitive
types when record by a `Visitor`, while those type infos is essential to
some people. For example, I need to show my spans in Jaeger UI.

Make the `tracing::instrument` records other function arguments as
`fmt::Debug ` while not for those primitive types.

However, I'm not good at naming. Maybe the `RecordType` enum and its
variant aren't a good name? I'd love to seek suggestions. Thanks.
2021-06-01 09:09:45 -07:00
Eliza Weisman
614a327adb chore: fix clippy's awful new "inconsistent struct constructor" lint (#1401)
This branch fixes some annoying new clippy lints no one cares about.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
# Conflicts:
#	tracing-subscriber/src/layer.rs
2021-05-17 13:35:53 -07:00
Eliza Weisman
742b21461b
attributes: prepare to release v0.1.15 (#1301)
# 0.1.15 (March 12, 2021)

### Fixed

- `#[instrument]` on functions returning `Box::pin`ned futures incorrectly
  skipping function bodies prior to returning a future ([#1297])

Thanks to @nightmared for contributing to this release!

[#1297]: https://github.com/tokio-rs/tracing/pull/1297
2021-03-12 12:51:54 -08:00
Simon THOBY
ac0aa9763b attributes: fix #[instrument] skipping code when returning pinned futures (#1297)
This backports #1297 from `master`.

Fixes #1296.

I had forgotten to use all the input statements in #1228, so we would
delete nearly all the statement of sync functions that return a boxed
future :/
2021-03-12 11:21:58 -08:00
Eliza Weisman
88611cbc98
attributes: prepare to release v0.1.14 (#1292)
### Fixed

- Compatibility between `#[instrument]` and `async-trait` v0.1.43 and
  newer ([#1228])

Thanks to @nightmared for lots of hard work on this fix!

[#1228]: https://github.com/tokio-rs/tracing/pull/1228
2021-03-10 13:07:00 -08:00
Eliza Weisman
8f68311276
attributes: update #[instrument] to support async-trait 0.1.43+ (#1228) (#1291)
This backports #1228 from `master` to `v0.1.x`.

It works with both the old and new version of async-trait (except for
one doc test that failed previously, and that works with the new
version). One nice thing is that the code is simpler (e.g.g no self
renaming to _self, which will enable some simplifications in the
future).

A minor nitpick is that I disliked the deeply nested pattern matching in
get_async_trait_kind (previously: get_async_trait_function), so I
"flattened" that a bit.

Fixes  #1219.

Co-authored-by: Simon THOBY <git@nightmared.fr>
2021-03-10 12:44:19 -08:00
Eliza Weisman
7f3d94f485
attributes: prepare to release v0.1.13 (#1243)
### Fixed

- Compiler error when using `#[instrument(err)]` on functions which
  return `impl Trait` ([#1236])

[#1236]: https://github.com/tokio-rs/tracing/pull/1236

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-02-17 15:14:07 -08:00
Lars Francke
9d4b7e7a3a
tracing: fix a typo and adds a note about the supported field syntax (#1232)
The `instrument` macro does not explain the syntax that can be used and
the main tracing docs only say that this syntax is valid for `span` and
`event` macros.

Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2021-02-17 14:02:01 -08:00
Eliza Weisman
e1e3431bc4
attributes: fix #[instrument(err)] with impl Trait return types (#1236)
This backports PR #1233 to v0.1.x. This isn't *just* a simple cherry-pick
because the new tests in that branch use the v0.2.x module names, so
that had to be fixed. Otherwise, though, it's the same change, and I'll go
ahead and merge it when CI passes, since it was approved on `master`.

## Motivation

Currently, using `#[instrument(err)]` on a function returning a `Result`
with an `impl Trait` in it results in a compiler error. This is because
we generate a type annotation on the closure in the function body that
contains the user function's actual body, and `impl Trait` isn't allowed
on types in local bindings, only on function parameters and return
types.

## Solution

This branch fixes the issue by simply removing the return type
annotation from the closure. I've also added tests that break on master
for functions returning `impl Trait`, both with and without the `err`
argument.

Fixes #1227

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-02-11 12:24:48 -08:00
Eliza Weisman
a3f2c0c116
attributes: prepare to release v0.1.12 (#1221)
### Fixed

- Compiler error when using `#[instrument(err)]` on functions with
  mutable parameters ([#1167])
- Missing function visibility modifier when using `#[instrument]` with
  `async-trait` ([#977])
- Multiple documentation fixes and improvements ([#965], [#981],
  [#1215])

 ### Changed

- `tracing-futures` dependency is no longer required when using
  `#[instrument]` on async functions ([#808])

Thanks to @nagisa, @Txuritan, @TaKO8Ki, and @okready for contributing to
this release!

[#1167]: https://github.com/tokio-rs/tracing/pull/1167
[#977]: https://github.com/tokio-rs/tracing/pull/977
[#965]: https://github.com/tokio-rs/tracing/pull/965
[#981]: https://github.com/tokio-rs/tracing/pull/981
[#1215]: https://github.com/tokio-rs/tracing/pull/1215
[#808]: https://github.com/tokio-rs/tracing/pull/808
2021-02-04 12:41:12 -08:00