67 Commits

Author SHA1 Message Date
Jonas Platte
c297a37096 tracing-subscriber: Switch to unconditional no_std 2025-09-08 17:36:08 +02:00
Oscar Gustafsson
b3aa9de4c5 subscriber: update matchers to 0.2 (#3033)
Update the version of the `matchers` crate to 0.2. This requires also
adding a direct dependency on `regex-automata` to enable the `std`
feature.
2025-06-03 09:47:35 +02:00
Hayden Stainsby
f006df25b4 chore: fix Rust 1.86.0 lints (#3253)
There was a single case of the new
[`clippy::double_ended_iterator_last`] lint which was triggered in
`tracing-attributes` and needed to be fixed.

There were also a number of cases of incorrectly indented lines, caught
in [`clippy::doc_overindented_list_items`].

[`clippy::double_ended_iterator_last`]: https://rust-lang.github.io/rust-clippy/master/index.html#double_ended_iterator_last
[`clippy::doc_overindented_list_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#doc_overindented_list_items
2025-06-03 09:47:35 +02:00
Eric Seppanen
11c8273035
subscriber: don't gate with_ansi() on the "ansi" feature (#3020)
The commit 1cb523b87d3d removed this cfg gate on master. However, when
the change was backported in 1cb523b87d3d the docs were updated but the
cfg change was omitted.

This made the docs misleading, since they say "This method itself is
still available without the feature flag."
2024-11-25 22:43:30 +01:00
David Barsky
c6abc10c3a chore: bump MSRV to 1.63 (#2793) 2023-11-07 13:37:19 -08:00
Eliza Weisman
e03a831d05 chore: fix new warnings in Rust 1.72.0 (#2700)
This branch fixes a handful of new warnings which have shown up after
updating to Rust 1.72.0.

This includes:

* `clippy::redundant_closure_call` in macros --- allowed because the
  macro sometimes calls a function that isn't a closure, and the closure
  is just used in the case where it's not a function.
* Unnecessary uses of `#` in raw string literals that don't contain `"`
  characters.
* Dead code warnings with specific feature flag combinations in
  `tracing-subscriber`.

In addition, I've fixed a broken RustDoc link that was making the
Netlify build sad.
2023-10-01 10:46:02 -07:00
daxpedda
049ad730c1 subscriber: add ability to disable ANSI without crate feature (#2532)
## Motivation

Currently it is not possible to disable ANSI in `fmt::Subscriber`
without enabling the "ansi" crate feature. This makes it difficult for
users to implement interoperable settings that are controllable with
crate features without having to pull in the dependencies "ansi" does.

I hit this while writing an application with multiple logging options
set during compile-time and I wanted to cut down on dependencies if
possible.

## Solution

This changes `fmt::Subscriber::with_ansi()` to not require the "ansi"
feature flag. This way, `with_ansi(false)` can be called even when the
"ansi" feature is disabled. Calling `with_ansi(true)` when the "ansi"
feature is not enabled will panic in debug mode, or print a warning if
debug assertions are disabled.

Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2023-04-21 16:59:51 -07:00
David Barsky
45a2cea8bb subscriber: dim Compact targets, matching the default formatter (#2409)
Fixes https://github.com/tokio-rs/tracing/issues/2408

Just switch to use `dim`

Before:
![2022-12-08_13-58-40](https://user-images.githubusercontent.com/623453/206576169-63ee4e20-b56f-4c63-a9b3-80ba2e97eec9.png)
After:
![2022-12-08_13-55-36](https://user-images.githubusercontent.com/623453/206576055-878d360f-7b95-4e18-bc31-4fb6f1b71a3a.png)
Full mode for comparison:
![2022-12-08_13-55-48](https://user-images.githubusercontent.com/623453/206576054-6e38852c-cb3a-4b84-98e5-50463cdb5073.png)
; Conflicts:
;	tracing-subscriber/src/fmt/format/mod.rs
2023-04-21 16:59:51 -07:00
Kartavya Vashishtha
1b89aa950a subscriber: mark builders as must_use (#2239)
## Motivation

Builders not marked `#[must_use]` can not be initialized sometimes,
causing silent failures.
Eg.
```rust
fn main() {
    tracing_subscriber::fmt();
    tracing::info!("hello");
}
```
won't print anything.

## Solution

Added `#[must_use]` to builder types in the tracing-subscriber crate.
2022-07-28 17:13:52 -07:00
Chris Burgess
b6762daf52
subscriber: correct fmt::init() documentation (#2224)
## Motivation

Previously the documentation for `fmt::init()` was misleading. It stated
that it was shorthand for `fmt().init()`. This lead to confusion as
users would expect the same behavior from both. However `fmt::init()`
would, whether you used the env-filter feature or not, rely on RUST_LOG
to set the tracing level. `fmt().init()` does not do this and it must be
set with a specific configuration via `with_env_filter`.

## Solution

The documentation has been updated to no longer state that it is 1:1
shorthand for the other. The documentation now specifically points out
that you must be using the `env-filter` feature and gives a correct
example to mimic the `fmt::init()` behavior using `fmt().init()`.

Fixes #2217
Fixes #1329

Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2022-07-28 18:56:03 +00:00
Bryan Garza
e4a6b5745f
subscriber: if error occurs when formatting event, write error to Writer (#2102)
Motivation:
When `Format_event::format_event(...)` returns an error, we are
currently silently dropping that
Event. https://github.com/tokio-rs/valuable/issues/88 explains one
such case in which this was encountered (due to a bug in
valuable-serde). We want to be made aware whenever an Event is dropped.

Solution:
Write to the Writer with an error message to let the user know that
we were unable to format a specific event. If writing to the Writer fails,
we fall back to writing to stderr. We are not emitting an actual tracing
Event, to avoid the risk of a cycle (the new Event could trigger the
same formatting error again).

Resolves #1965.

Co-authored-by: Eliza Weisman <eliza@buoyant.io>
Co-authored-by: David Barsky <me@davidbarsky.com>
2022-07-25 09:44:27 -07:00
Christopher Durham
f42e7e6dd2 core, subscriber: add event_enabled to filter events on fields (#2008)
## Motivation

Allow filter layers to filter on the contents of events (see #2007).

## Solution

This branch adds a new `Subscriber::event_enabled` method, taking an
`Event` and returning `bool`. This is called before the
`Subscriber::event` method, and if it returns `false`,
`Subscriber::event` is not called.

For simple subscriber (e.g. not using `Layer`s), the `event_enabled`
method is not particulary necessary, as the subscriber can just skip the
`event` call. However, this branch also adds a new
`Layer::event_enabled` method, with the signature:
```rust
fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool;
```

This is called before `Layer::on_event`, and if `event_enabled`
returns `false`, `on_event` is not called (nor is `Subscriber::event`).
This allows filter `Layer`s to filter out an `Event` based on its
fields.

Closes #2007
2022-06-22 15:01:24 -07:00
David Barsky
f90b4dc97a
chore: backport #2126 (#2127) 2022-05-16 17:24:43 +00: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
Eliza Weisman
94379a36ff docs: clean up tracing_subscriber::fmt formatter docs (#1927)
## Motivation

Currently, the documentation for the `fmt` module shows examples of the
output for each formatter in the top-level module. This is a lot of text
that makes finding other things in the documentation more difficult.
Meanwhile, the type-level docs for the various formatters are quite
terse and don't offer much useful information.

## Solution

This branch moves the example output to the type-level docs for the
various formatters, and links to it from the list of formatters. I've
also updated and expanded some of the documentation for the formatters,
and added a similar list of formatters to the `fmt::format` module.
Hopefully, this makes things easier to navigate?

Finally, I've re-generated all example output with the latest versions
of each formatter.

## Alternatives

Alternatively, we could not move the example output. The initial
intention for putting it in the top-level `fmt` module docs was to make
it _very_ easy to find what the different formats look like. Perhaps
this is worth having a lot of text to scroll through in the
module-level docs?
2022-02-17 12:21:18 -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
Lily Ballard
bcd0972762
subscriber: Add SubscriberBuilder/Layer accessors (#1871)
## Motivation

`SubscriberBuilder`s and `Layer`s configured with custom event/field
formatters do not provide any means of accessing or mutating those
formatters. Any configuration that needs to be done must be done before
setting them on the builder/layer. This is frustrating as it makes it
difficult to provide a pre-configured API akin to
`tracing_subscriber::fmt()` along with accessors like `.compact()` that
modify the formatter.

## Solution

Add accessors `.map_event_format()` and `.map_fmt_fields()` to
`SubscriberBuilder` and `Layer` that map the existing formatter through
a closure. This allows the closure to modify it or to derive a new
formatter from it with a different type.

Also add a `.map_writer()` method that does the same thing for the
`MakeWriter`, to round out the accessors for the various type
parameters.

The filter type is currently restricted to just `LevelFilter` or
`EnvFilter` and so this does not add a corresponding `.map_filter()`.
That can be added later if we add the ability to attach arbitrary
filters.

Also fix some minor docs issues that were spotted as part of
implementing this.

Fixes #1756
2022-01-28 17:50:17 +00:00
Renê Couto e Silva
35d177626b subscriber: add Format::with_file and with_line_number (#1773)
## Motivation

Logging line numbers and file names can be useful for debugging. This
feature was suggested by #1326

## Solution

As per @hawkw's suggestions, fields were added on `Format`, along with
builder methods. Filename and line number information was gathered from
the `meta` variable.

The `Pretty` formatter already supports printing source locations, but
this is configured separately on the `Pretty` formatter rather than on
the `Format` type. This branch also changes `Pretty` to honor the
`Format`-level configurations and deprecates the `Pretty`-specific
method.

Fixes #1326 Closes #1804

Co-authored-by: David Barsky <me@davidbarsky.com>
Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2022-01-14 12:12:09 -08:00
Eliza Weisman
1a81e0d95b subscriber: fix broken docs links (#1825)
Apparently the links to the `Default::default()` methods didn't actually
work! Or, maybe they did work, but they don't on the latest nightly?

Regardless, this fixes them (as well as the RustDoc errors).

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2022-01-14 12:12:09 -08:00
Tatsuyuki Ishi
c60c530ab6
subscriber: use Targets as the default filter if env-filter is not enabled(#1781)
The removal of `env-filter` from the default features in 0.3.0 has
caused a lot of developer frustration. This PR changes
`tracing_subscriber::fmt::init()` and `try_init` to fall back to adding
a `Targets` filter parsed from the `RUST_LOG` environment variable,
rather than a `LevelFilter` with the default max level.

This way, `RUST_LOG`-based filtering will still "just work" out of the
box with the default initialization functions, regardless of whether or
not `EnvFilter` is enabled.

Closes #1697

Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2021-12-29 15:28:37 -08:00
Arpad Borsos
538615030d subscriber: update tracing_subscriber::fmt docs (#1690)
Brings the `fmt` docs in line with the crate docs.
2021-11-30 16:16:59 -08:00
Eliza Weisman
f86322a464 subscriber: "implementing FormatEvent" docs (#1727)
This branch adds some documentation to the `FormatEvent` trait in
`tracing_subscriber::fmt` on how to write user-provided `FormatEvent`
implementations. There's probably room for additional improvement here,
but I just wanted to get something written down for now.

I also fixed a broken link I noticed while I was here.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
Co-authored-by: David Barsky <me@davidbarsky.com>
2021-11-19 16:57:37 -08:00
Eliza Weisman
a927607fdf
subscriber: remove deprecated APIs (#1673)
## Motivation

`tracing-subscriber` currently contains some APIs that were deprecated
in the v0.2.x series:
- `fmt::LayerBuilder`, which is now a type alias for `fmt::Layer` (as
  the `Layer` type can expose all the same methods as the builder)
- `registry::SpanRef::parent_id`, which doesn't play nice with per-layer
  filtering,
- `fmt::Layer::inherit_fields`, which no longer does anything as it's
  now the default behavior
- `fmt::Layer::on_event`, which was renamed to `fmt_event`
- the `SpanRef::parents` and `layer::Context::scope` iterators, which
  were replaced by the APIs added in #1431 and #1434

Prior to releasing v0.3, the deprecated APIs should be removed.

## Solution

This branch deletes the deprecated APIs, with the exception of
`SpanRef::parents` and `Context::scope` (which were already removed in
240d11a7ef70c1197f8071d98db74a02bd58fad9).

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-10-22 10:28:18 -07:00
Eliza Weisman
e82596842c subscriber: minor feature flagging fixup
This fixes unused code warnings with the default featureset.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-10-21 12:39:23 -07:00
Eliza Weisman
240d11a7ef subscriber: add minimal #![no_std] support (#1648)
Backports #1648 from `master`.

Depends on #1649

## Motivation

Presently, the `tracing-subscriber` crate requires the Rust standard
library and doesn't build with `#![no_std]` targets. For the most part,
this is fine, as much of `tracing-subscriber` inherently depends on
`std` APIs.

However, `tracing-subscriber` also contains some key abstractions that
are necessary for interoperability: the `Layer` and `LookupSpan`
traits. Since these traits are in `tracing-subscriber`, `no-std` users
cannot currently access them.

Some of the other utilities in this crate, such as the field visitor
combinators, may also be useful for `#![no_std]` projects.

## Solution

This branch adds "std" and "alloc" feature flags to
`tracing-subscriber`, for conditionally enabling `libstd` and
`liballoc`, respectively. The `registry`, `fmt`, `EnvFilter`, and
`reload` APIs all require libstd, and cannot be implemented without it,
but the core `Layer` and `LookupSpan` traits are now available with
`#![no_std]`.

Fixes #999

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-10-21 12:39:23 -07:00
Eliza Weisman
3634c9120f subscriber: replace chrono with time for timestamp formatting (#1646)
## Motivation

Currently, `tracing-subscriber` supports the `chrono` crate for
timestamp formatting, via a default-on feature flag. When this code was
initially added to `tracing-subscriber`, the `time` crate did not have
support for the timestamp formatting options we needed.

Unfortunately, the `chrono` crate's maintainance status is now in
question (see #1598). Furthermore, `chrono` depends on version 0.1 of
the `time` crate, which contains a security vulnerability
(https://rustsec.org/advisories/RUSTSEC-2020-0071.html). This
vulnerability is fixed in more recent releases of `time`, but `chrono`
still uses v0.1.

## Solution

Fortunately, the `time` crate now has its own timestamp formatting
support.

This branch replaces the `ChronoLocal` and `ChronoUtc` timestamp
formatters with new `LocalTime` and `UtcTime` formatters. These
formatters use the `time` crate's formatting APIs rather than
`chrono`'s. This removes the vulnerable dependency on `time` 0.1

Additionally, the new `time` APIs are feature flagged as an _opt-in_
feature, rather than as an _opt-out_ feature. This should make it easier
to avoid accidentally depending on the `time` crate when more
sophisticated timestamp formatting is _not_ required.

In a follow-up branch, we could also add support for `humantime` as an
option for timestamp formatting.

Naturally, since this removes existing APIs, this is a breaking change,
and will thus require publishing `tracing-subscriber` 0.3. We'll want to
do some other breaking changes as well.

Fixes #1598.
2021-10-21 12:39:23 -07:00
Eliza Weisman
6cc6c47354
subscriber: add lifetime parameter to MakeWriter (#781) (#1654)
This backports PR #781 from `master`.

## Motivation

Currently, the `tracing-subscriber` crate has the `MakeWriter` trait for
customizing the io writer used by `fmt`. This trait is necessary (rather
than simply using a `Write` instance) because the default implementation
performs the IO on the thread where an event was recorded, meaning that
a separate writer needs to be acquired by each thread (either by calling
a function like `io::stdout`, by locking a shared `Write` instance,
etc).

Right now there is a blanket impl for `Fn() -> T where T: Write`. This
works fine with functions like `io::stdout`. However, the _other_ common
case for this trait is locking a shared writer.

Therefore, it makes sense to see an implementation like this:

``` rust
impl<'a, W: io::Write> MakeWriter for Mutex<W>
where
    W: io::Write,
{
    type Writer = MutexWriter<'a, W>;
    fn make_writer(&self) -> Self::Writer {
        MutexWriter(self.lock().unwrap())
    }
}

pub struct MutexWriter<'a, W>(MutexGuard<'a, W>);

impl<W: io::Write> io::Write for MutexWriter<'_, W> {
    // write to the shared writer in the `MutexGuard`...
}
```

Unfortunately, it's impossible to write this. Since `MakeWriter` always
takes an `&self` parameter and returns `Self::Writer`, the generic
parameter is unbounded:
```
    Checking tracing-subscriber v0.2.4 (/home/eliza/code/tracing/tracing-subscriber)
error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
  --> tracing-subscriber/src/fmt/writer.rs:61:6
   |
61 | impl<'a, W: io::Write> MakeWriter for Mutex<W>
   |      ^^ unconstrained lifetime parameter

error: aborting due to previous error
```

This essentially precludes any `MakeWriter` impl where the writer is
borrowed from the type implementing `MakeWriter`. This is a significant
blow to the usefulness of the trait. For example, it prevented the use
of `MakeWriter` in `tracing-flame` as suggested in
https://github.com/tokio-rs/tracing/pull/631#discussion_r391138233.

## Proposal

This PR changes `MakeWriter` to be generic over a lifetime `'a`:

```rust
pub trait MakeWriter<'a> {
    type Writer: io::Write;

    fn make_writer(&'a self) -> Self::Writer;
}
```
The `self` parameter is now borrowed for the `&'a` lifetime, so it is
okay to return a writer borrowed from `self`, such as in the `Mutex`
case.

I've also added an impl of `MakeWriter` for `Mutex<T> where T: Writer`.

Unfortunately, this is a breaking change and will need to wait until we
release `tracing-subscriber` 0.3.

Fixes #675.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-10-19 16:45:14 -07:00
Eliza Weisman
ac4a8dd27c chore: fix inconsistent terminology
I noticed a handful of places where `v0.1.x` refers to `Subscriber`s as
 "collectors". This probably happened because we backported some commits
 from master and forgot to change every instance of "collector" back to
 "subscriber".

 This commit fixes that. Whoops.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-09-04 11:57:42 -07:00
Eliza Weisman
805eb51bc9 subscriber: add MakeWriter::make_writer_for (#1141)
This backports PR #1141 from `master`.

subscriber: add `MakeWriter::make_writer_for`

## Motivation

In some cases, it might be desirable to configure the writer used for
writing out trace data based on the metadata of the span or event being
written. For example, we might want to send different levels to
different outputs, write logs from different targets to separate files,
or wrap formatted output in ANSI color codes based on levels. Currently,
it's not possible for the `MakeWriter` trait to model this kind of
behavior --- it has one method, `make_writer`, which is completely
unaware of *where* the data being written came from.

In particular, this came up in PR #1137, when discussing a proposal that
writing to syslog could be implemented as a `MakeWriter` implementation
rather than as a `Subscribe` implementation, so that all the formatting
logic from `tracing_subscriber::fmt` could be reused. See [here][1] for
details.

## Solution

This branch adds a new `make_writer_for` method to `MakeWriter`, taking
a `Metadata`. Implementations can opt in to metadata-specific behavior
by implementing this method. The method has a default implementation
that just calls `self.make_writer()` and ignores the metadata, so it's
only necessary to implement this when per-metadata behavior is required.
This isn't a breaking change to existing implementations.

There are a couple downsides to this approach: it's possible for callers
to skip the metadata-specific behavior by calling `make_writer` rather
than `make_writer_for`, and the impls for closures can't easily provide
metadata-specific behavior.

Since the upcoming release is going to be a breaking change anyway, we
may want to just make the breaking change of having
`MakeWriter::make_writer` _always_ take a `Metadata`, which solves these
problems. However, that can't be backported to v0.1.x as easily. Additionally,
that would mean that functions like `io::stdout` no longer implement
`MakeWriter`; they would have to be wrapped in a wrapper type or closure
that ignores metadata.

[1]: https://github.com/tokio-rs/tracing/pull/1137#discussion_r542728604

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-06-25 17:01:47 -07:00
akinnane
07af5f8fd8 subscriber: fix span data for new, exit, and close events (#1334)
* subscriber: fix span data for new, exit, and close events

New, exit and close span events are generated while the current
context is set to either `None` or the parent span of the span the
event relates to. This causes spans data to be absent from the JSON
output in the case of the `None`, or causes the span data to reference
the parent's span data. Changing the way the current span is
determined allows the correct span to be identified for these
events. Trying to access the events `.parent()` allows access of the
correct span for the `on_event` actions, while using `.current_span()`
works for normal events.

Ref: #1032

* Fix style

* subscriber: improve test for #1333

Based on feedback by @hawkw, I've improved the test for #1333 to parse
the json output. This is more specifc for the bug and allows easier
testing of the different span `on_events`.

Ref: https://github.com/tokio-rs/tracing/pull/1333#pullrequestreview-623737828

* subscriber: improve #1334 tests covering all span states

Use the `on_records` test method check all events have the correct
context as described in the PR.

* Apply suggestions from code review

Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2021-04-17 14:48:07 -07:00
Eliza Weisman
84ff3a4f1c
chore: reverse the polarity of conversions, fix clippy (#1335)
This backports PR #1335 from `master` to `v0.1.x`.

Clippy now warns about implementing `Into` rather than `From`, since
`From` automatically provides `Into` but `Into` does not provide `From`.

This commit fixes the direction of those conversions, placating Clippy.

Additionally, it fixes a redundant use of slice syntax that Clippy also
complained about.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-03-29 16:35:50 -07:00
Zicklag
a947c5a63f subscriber: change FmtSpan to a combinable bitflag (#1277)
This backports #1277 from `master`.

Fixes #1136.

Allows arbitrarily combining different FmtSpan events to listen to.

Motivation
----------

The idea is to allow any combination of `FmtSpan` options, such as the
currently unachievable combination of `FmtSpan::NEW | FmtSpan::CLOSE`.

Solution
--------

Make `FmtSpan` behave like a bitflag that can be combined using the
bitwise or operator ( `|` ) while maintaining backward compatibility by
keeping the same names for all existing presets and keeping the
implementation details hidden.
2021-03-12 11:21:58 -08:00
Folyd
51812267b8 subscriber: use struct update syntax when constructing from self (#1289)
This backports #1289 from `master`.

This PR aims to remove a lot of initializer boilerplate code by adopting
the`struct update syntax.  If the [RFC 2528]  gets merged and
implemented, we can remove more. 😸

[RFC 2528]: https://github.com/rust-lang/rfcs/pull/2528
2021-03-12 11:21:58 -08:00
Eliza Weisman
8d83326a5f subscriber: fix FmtCollector not forwarding max level (#1251)
The `FmtCollector` type is missing a `Collect::max_level_hint
method that forwards the inner stack's max level hint.

This fixes that, and adds tests.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-02-19 14:18:39 -08:00
Eliza Weisman
31aa6afecc subscriber: set the max log LevelFilter in init (#1248)
Depends on #1247.

Since `tracing-subscriber`'s `init` and `try_init` functions set the
global default subscriber, we can use the subscriber's max-level hint as
the max level for the log crate, as well. This should significantly
improve performance for skipping `log` records that fall below the
collector's max level, as they will not have to call the
`LogTracer::enabled` method.

This will prevent issues like bytecodealliance/wasmtime#2662
from occurring in the future. See also #1249.

In order to implement this, I also changed the `FmtSubscriber`'s
`try_init` to just use `util::SubscriberInitExt`'s `try_init` function,
so that the same code isn't duplicated in multiple places. I also
added `AsLog` and `AsTrace` conversions for `LevelFilter`s in
the `tracing-log` crate.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2021-02-18 16:37:09 -08:00
Eliza Weisman
8bdc6c367d
subscriber: add Pretty formatter (backports #1067) (#1080)
This backports PR #1067 to v0.1.x. Since this has already been approved
on master, I'm just going to go ahead and merge it when CI passes.

## Motivation

Currently, the `tracing_subscriber::fmt` module contains only
single-line event formatters. Some users have requested a
human-readable, pretty-printing event formatter optimized for
aesthetics.

## Solution

This branch adds a new `Pretty` formatter which uses an _excessively_
pretty output format. It's neither compact, single-line oriented, nor
easily machine-readable, but it looks _quite_ nice, in my opinion. This
is well suited for local development or potentially for user-facing logs
in a CLI application.

Additionally, I tried to improve the docs for the different formatters
currently provided, including example output. Check out [the Netlify
preview][1]!

[1]: https://deploy-preview-1067--tracing-rs.netlify.app/tracing_subscriber/fmt/index.html#formatters

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2020-11-02 13:20:46 -08:00
samrg472
ea633f5983
subscriber: Implement TestWriter to capture logs in cargo test (#938) 2020-08-19 13:44:53 -04:00
Tarun Pothulapati
c109197c3e
subscriber: allow thread name and ID to be displayed in traces (#818)
## Motivation

Fixes #809 

## Solution

This PR adds two new methods i.e `with_thread_ids` and
`with_thread_names` to the fmt Layer which passed till
the pre-configured Format type, where the check is performed
and these the above values are formatted based on the flags.

The formatting is done by creating to new Types that impl Display
for Id and Name. For Thread Name, we keep track of the max length
of the thread name that occured till now using a thread safe static
type and pad accordingly. For Thread Id, we pad directly with 2
as in most cases we would see a double digit number of threads.

Signed-off-by: Tarun Pothulapati <tarunpothulapati@outlook.com>
2020-07-17 10:09:59 -07:00
François
edbf22b042
subscriber: add nested spans in json formatter (#741)
## Motivation

Nested spans are not available in json formatter

## Solution

I added a field `spans` in the json, with an array of the nested spans.
I reused the span representation from the existing `span`, and pushed
all the span representation in a `vec` using `ctx.visit_spans`. I didn't
remove the `span` field as it can be useful to have direct access to the
current span

Fixes: #704
2020-07-09 15:48:42 -07:00
Roland Kuhn
50e857414c
subscriber: add synthesized span events to fmt (#761)
## Motivation

Currently there is no subscriber that comes out of the box that will
print information about spans. I find the concept quite useful and
instrumented some code that does database queries in order to print out
how long things take as well as tracing the execution (i.e. each span is
doubling as a log statement of the same level). 

## Solution

This branch adds a new feature to `tracing-subscriber`'s `fmt` module
that adds the option to print events when spans are opened, entered,
exited, and closed`. This is done by synthesizing an event that is then
passed to the format layer's `on_event` method, allowing us to use the
configured event format without needing to add more hooks for lifecycle
events (one of the downsides of the approach used in #450). Which span
lifecycle events generate synthesized events is user-configurable. When
timestamps are enabled, the span close events will also include fields
for the span's _busy time_ (entered) and _idle time_ (total lifetime -
busy time). Example output looks like the following:

![image](https://user-images.githubusercontent.com/470469/85235218-9e36ef00-b413-11ea-9aa7-e6439bc2f604.png)

Closes #450
Closes #161
2020-06-30 14:09:02 -07:00
Eliza Weisman
62e0cc0a03
subscriber: add more ergonomic subscriber configuration APIs (#660)
* subscriber: add less-verbose configuration APIs

Signed-off-by: Eliza Weisman <eliza@buoyant.io>

* even nicer easymode

Signed-off-by: Eliza Weisman <eliza@buoyant.io>

* wip## Motivation

Users have said fairly frequently that configuring new subscribers in an
application is unnecessarily verbose and confusing. We should try to
make this nicer, especially as it's a common "on ramp" for new `tracing`
users.

## Solution 

This branch adds new APIs, inspired by `tonic` and `warp`, that should
make setting up a subscriber a little less verbose. This includes:

- Many modules in `tracing-subscriber` now expose free functions 
  that construct default instances of various types. This makes 
  configuring subscribers using these types more concise, a la `warp`.
- An extension trait for adding `.set_default`, `.init`, and `.try_init` 
  methods to subscribers. This generalizes the similar functions on
  `fmt`'s `SubscriberBuilder` to work with other subscribers.

All the old APIs are still left as they were previously. The new APIs
just provide shorthand for them.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2020-04-03 18:04:23 -07:00
Eliza Weisman
887f79173f
subscriber: move fmt::LayerBuilder methods to fmt::Layer (#655)
## Motivation

There isn't an actual reason that `fmt::Layer` needs a separate builder
type, since the builder and layer structs are identical and only differ
in what methods they provide. If the methods for configuring a `Layer`
were exposed by the `Layer` type instead, it would be simple to
construct `Layer`s — no need to call `.finish()` on the builder.

## Solution

This commit moves all the `LayerBuilder` methods to `Layer`, makes
`LayerBuilder` a type alias for `Layer`, and deprecates
`Layer::builder`, the `LayerBuilder` type, and `LayerBuilder::finish()`.
Since nothing has been removed, this shouldn't be a breaking change, but
we can remove the deprecated APIs in 0.3.x.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2020-04-02 08:44:28 -07:00
Lucio Franco
7e8b1140bf
subscriber: Flatten json event metadata (#599)
Signed-off-by: Lucio Franco <luciofranco14@gmail.com>
Co-authored-by: Eliza Weisman <eliza@buoyant.io>
2020-02-27 17:02:42 -05:00
Jakub Beránek
a457c988d1
fmt: Support disabling the target in formatted output (#594)
This PR adds support for disabling level in formatted output.

Fixes: #592
2020-02-21 15:06:43 -08:00
Eliza Weisman
e32012a64a
subscriber: improve docs on Layer composition (#566)
Depends on #564 

This commit adds a new section to the `Layer` docs on how `Layer`s and
`Subscriber`s are composed. Additionally, it updates the docs to prefer
the use of `SubscriberExt::with` over `Layer::with_subscriber`.

Additionally, I've fixed how `SubscriberExt::with` is implemented, so
that `Layer`s may use `with_subscriber` as a callback for composition.

Closes  #452
Closes #505 (IMO)
2020-02-04 14:03:48 -08:00
Eliza Weisman
a661155590
subscriber: remove LookupMetadata trait (#564)
## Motivation

The `LookupMetadata` trait was essentially a prototype for `LookupSpan`,
and was intended to allow subscribers to implement more granular sets of
"registry" behavior. However, in practice, nothing ended up using it and
it was generally eclipsed by `LookupSpan`. The model of allowing
`Layer` implementations to opt in to more granular capabilities doesn't
make a whole lot of sense when there are only two such traits available
and one is a more powerful superset of the other. Before we release
`tracing-subscriber` 0.2.0, we should try to remove any APIs that aren't
necessary, since removing them later is a breaking change.

## Solution

Therefore, this commit removes `LookupMetadata`, and rewrites the
`Context::metadata` method to use `LookupSpan` to look up the metadata,
instead.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
2020-02-04 13:28:09 -08:00
Eliza Weisman
c3c0bd5238
docs: finish doc_cfg for tracing-futures and tracing-subscriber (#525) (#528)
* Get the last bits of tracing-core

* remove unnecessary doc_cfgs

* add doc_cfg for std feature in tracing-futures

* Finish enabling doc_cfg for tracing-futures

* fix tracing-futures doc_cf and start subscriber

* finish doc_cfg for tracing-subscriber

Authored-by: Jane Lusby <jlusby42@gmail.com>
2020-01-10 15:15:14 -08:00
Jane Lusby
f9c75340f9 subscriber: add examples for layers (#510)
* Add examples for layers

* Reorganize and shrink examples

* Apply suggestions from code review

Co-Authored-By: Eliza Weisman <eliza@buoyant.io>

* Clean up imports

* remove module specific filtering

* add an explanation

Co-authored-by: Eliza Weisman <eliza@buoyant.io>

Closes #430
2020-01-07 15:47:10 -08:00
Arthur Gautier
1f0bdeec73 subscriber: fixup various compilation errors with no-default-features (#500)
* subscriber: compilation errors w/ nodefault + ansi

when compiling with -no-default-features --features "ansi", the
following compilation error would come up:
```
error[E0599]: no method named `with_env_filter` found for type `fmt::SubscriberBuilder` in the current scope
   --> tracing-subscriber/src/fmt/mod.rs:663:10
    |
146 | / pub struct SubscriberBuilder<
147 | |     N = format::DefaultFields,
148 | |     E = format::Format<format::Full>,
149 | |     F = LevelFilter,
...   |
153 | |     inner: LayerBuilder<Registry, N, E, W>,
154 | | }
    | |_- method `with_env_filter` not found for this
...
663 |           .with_env_filter(crate::EnvFilter::from_default_env())
    |            ^^^^^^^^^^^^^^^ method not found in `fmt::SubscriberBuilder`
```

* subscriber: compilation errors w/ nodefault + fmt

when compiling with -no-default-features --features "fmt", the following
compilation error would come up:
```
error[E0107]: wrong number of type arguments: expected 2, found 1
   --> tracing-subscriber/src/fmt/format/mod.rs:603:30
    |
603 | impl<'a, N> fmt::Display for FullCtx<'a, N>
    |                              ^^^^^^^^^^^^^^ expected 2 type arguments
```

* subscriber: compilation errors w/ nodefault + env-filter + fmt

when compiling with -no-default-features --features "env-filter fmt", the
following compilation error would come up:

```
error[E0277]: the trait bound `for<'lookup> <S as registry::LookupSpan<'_>>::Data: registry::LookupSpan<'lookup>` is not satisfied
   --> tracing-subscriber/src/fmt/format/mod.rs:304:44
    |
279 |     ) -> fmt::Result {
    |                     - help: consider further restricting the associated type: `where for<'lookup> <S as registry::LookupSpan<'_>>::Data: registry::LookupSpan<'lookup>`
...
304 |         write!(writer, "{} {}", fmt_level, fmt_ctx)?;
    |                                            ^^^^^^^ the trait `for<'lookup> registry::LookupSpan<'lookup>` is not implemented for `<S as registry::LookupSpan<'_>>::Data`
    |
    = note: required because of the requirements on the impl of `std::fmt::Display` for `fmt::format::FmtCtx<'_, S, N>`
    = note: required by `std::fmt::Display::fmt`

error[E0593]: closure is expected to take 1 argument, but it takes 2 arguments
   --> tracing-subscriber/src/fmt/format/mod.rs:530:18
    |
530 |         self.ctx.visit_spans(|_, span| {
    |                  ^^^^^^^^^^^ --------- takes 2 arguments
    |                  |
    |                  expected closure that takes 1 argument
```

Closes #494
2020-01-02 11:01:25 -08:00