Struct SubscriberBuilder

Source
pub struct SubscriberBuilder<W = fn() -> Stdout, T = SystemTime, F = LevelFilter> { /* private fields */ }
Expand description

Configures and constructs Subscribers.

This should be this library’s replacement for tracing_subscriber::fmt::SubscriberBuilder.

Returns a new SubscriberBuilder for configuring a formatting subscriber. The default value should be mostly equivalent to calling tracing_subscriber::fmt().json().

§Examples

Using init to set the default subscriber:

json_subscriber::fmt::SubscriberBuilder::default().init();

Configuring the output format:

json_subscriber::fmt()
    // Configure formatting settings.
    .with_target(false)
    .with_timer(tracing_subscriber::fmt::time::uptime())
    .with_level(true)
    // Set the subscriber as the default.
    .init();

try_init returns an error if the default subscriber could not be set:

use std::error::Error;

fn init_subscriber() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
    json_subscriber::fmt()
        // This is no-op. This subscriber uses only JSON.
        .json()
        // Configure the subscriber to flatten event fields in the output JSON objects.
        .flatten_event(true)
        // Set the subscriber as the default, returning an error if this fails.
        .try_init()?;

    Ok(())
}

Rather than setting the subscriber as the default, finish returns the constructed subscriber, which may then be passed to other functions:

let subscriber = json_subscriber::fmt()
    .with_max_level(tracing::Level::DEBUG)
    .finish();

tracing::subscriber::with_default(subscriber, || {
    // the subscriber will only be set as the default
    // inside this closure...
})

Implementations§

Source§

impl<W, T, F> SubscriberBuilder<W, T, F>
where W: for<'writer> MakeWriter<'writer> + Send + Sync + 'static, T: FormatTime + Send + Sync + 'static, F: Layer<Layered<JsonLayer<Registry, W>, Registry>> + 'static, Layered<F, Layered<JsonLayer<Registry, W>, Registry>>: Subscriber + Into<Dispatch>,

Source

pub fn finish(self) -> Layered<F, Layered<JsonLayer<Registry, W>, Registry>>

Finish the builder, returning a new Subscriber which can be used to lookup spans.

Source

pub fn try_init(self) -> Result<(), Box<dyn Error + Send + Sync + 'static>>

Install this Subscriber as the global default if one is not already set.

If the tracing-log feature is enabled, this will also install the LogTracer to convert Log records into tracing Events.

§Errors

Returns an Error if the initialization was unsuccessful, likely because a global subscriber was already installed by another call to try_init.

Source

pub fn init(self)

Install this Subscriber as the global default.

If the tracing-log feature is enabled, this will also install the LogTracer to convert Log records into tracing Events.

§Panics

Panics if the initialization was unsuccessful, likely because a global subscriber was already installed by another call to try_init.

Source§

impl<W, T, F> SubscriberBuilder<W, T, F>

Source

pub fn json(self) -> Self

👎Deprecated: Calling json() does nothing.

This does nothing. It exists only to mimic tracing-subscriber’s API.

Source

pub fn with_ansi(self, _ansi: bool) -> Self

👎Deprecated: Calling with_ansi() does nothing.

This does nothing. It exists only to mimic tracing-subscriber’s API.

Source

pub fn with_writer<W2>(self, make_writer: W2) -> SubscriberBuilder<W2, T, F>
where W2: for<'writer> MakeWriter<'writer> + 'static,

Sets the MakeWriter that the SubscriberBuilder being built will use to write events.

§Examples

Using stderr rather than stdout:

use std::io;

let fmt_subscriber = json_subscriber::fmt()
    .with_writer(io::stderr);
Source

pub fn writer(&self) -> &W

Borrows the writer for this subscriber.

Source

pub fn writer_mut(&mut self) -> &mut W

Mutably borrows the writer for this subscriber.

This method is primarily expected to be used with the reload::Handle::modify method.

§Examples
use tracing_subscriber::{fmt::writer::EitherWriter, reload};
let subscriber = json_subscriber::fmt()
    .with_writer::<Box<dyn Fn() -> EitherWriter<_, _>>>(Box::new(|| EitherWriter::A(std::io::stderr())));
let (subscriber, reload_handle) = reload::Layer::new(subscriber);

tracing::info!("This will be logged to stderr");
reload_handle.modify(|subscriber| *subscriber.writer_mut() = Box::new(|| EitherWriter::B(std::io::stdout())));
tracing::info!("This will be logged to stdout");
Source

pub fn with_test_writer(self) -> SubscriberBuilder<TestWriter, T, F>

Configures the subscriber to support libtest’s output capturing when used in unit tests.

See TestWriter for additional details.

§Examples

Using TestWriter to let cargo test capture test output:

let fmt_subscriber = json_subscriber::fmt::fmt()
    .with_test_writer();
Source

pub fn log_internal_errors(self, log_internal_errors: bool) -> Self

Sets whether to write errors during internal operations to stderr. This can help identify problems with serialization and with debugging issues.

Defaults to false.

Source

pub fn map_writer<W2>( self, f: impl FnOnce(W) -> W2, ) -> SubscriberBuilder<W2, T, F>
where W2: for<'writer> MakeWriter<'writer> + 'static,

Updates the MakeWriter by applying a function to the existing MakeWriter.

This sets the MakeWriter that the subscriber being built will use to write events.

§Examples

Redirect output to stderr if level is <= WARN:

use tracing::Level;
use tracing_subscriber::fmt::writer::MakeWriterExt;

let stderr = std::io::stderr.with_max_level(Level::WARN);
let subscriber = json_subscriber::fmt::fmt()
    .map_writer(move |w| stderr.or_else(w));
Source

pub fn flatten_event(self, flatten_event: bool) -> SubscriberBuilder<W, T, F>

Sets the JSON subscriber being built to flatten event metadata.

Source

pub fn with_current_span( self, display_current_span: bool, ) -> SubscriberBuilder<W, T, F>

Sets whether or not the formatter will include the current span in formatted events.

Source

pub fn with_span_list( self, display_span_list: bool, ) -> SubscriberBuilder<W, T, F>

Sets whether or not the formatter will include a list (from root to leaf) of all currently entered spans in formatted events.

Source

pub fn with_timer<T2>(self, timer: T2) -> SubscriberBuilder<W, T2, F>

Use the given timer for log message timestamps.

See the tracing_subscriber::fmt::time module for the provided timer implementations.

Note that using the time feature flag on tracing_subscriber enables the additional time formatters UtcTime and LocalTime, which use the time crate to provide more sophisticated timestamp formatting options.

Source

pub fn without_time(self) -> SubscriberBuilder<W, (), F>

Do not emit timestamps with log messages.

Source

pub fn with_target(self, display_target: bool) -> SubscriberBuilder<W, T, F>

Sets whether or not an event’s target is displayed.

Source

pub fn with_file(self, display_filename: bool) -> SubscriberBuilder<W, T, F>

Sets whether or not an event’s source code file path is displayed.

Source

pub fn with_line_number( self, display_line_number: bool, ) -> SubscriberBuilder<W, T, F>

Sets whether or not an event’s source code line number is displayed.

Source

pub fn with_level(self, display_level: bool) -> SubscriberBuilder<W, T, F>

Sets whether or not an event’s level is displayed.

Source

pub fn with_thread_names( self, display_thread_name: bool, ) -> SubscriberBuilder<W, T, F>

Sets whether or not the name of the current thread is displayed when formatting events.

Source

pub fn with_thread_ids( self, display_thread_id: bool, ) -> SubscriberBuilder<W, T, F>

Sets whether or not the thread ID of the current thread is displayed when formatting events.

Source

pub fn with_opentelemetry_ids(self, display_opentelemetry_ids: bool) -> Self

Available on crate feature opentelemetry only.

Sets whether or not OpenTelemetry trace ID and span ID is displayed when formatting events.

Source

pub fn with_env_filter( self, filter: impl Into<EnvFilter>, ) -> SubscriberBuilder<W, T, EnvFilter>

Available on crate feature env-filter only.

Sets the EnvFilter that the collector will use to determine if a span or event is enabled.

Note that this method requires the “env-filter” feature flag to be enabled.

If a filter was previously set, or a maximum level was set by the with_max_level method, that value is replaced by the new filter.

§Examples

Setting a filter based on the value of the RUST_LOG environment variable:

use tracing_subscriber::EnvFilter;

json_subscriber::fmt()
    .with_env_filter(EnvFilter::from_default_env())
    .init();

Setting a filter based on a pre-set filter directive string:

json_subscriber::fmt()
    .with_env_filter("my_crate=info,my_crate::my_mod=debug,[my_span]=trace")
    .init();

Adding additional directives to a filter constructed from an env var:

use tracing_subscriber::filter::{EnvFilter, LevelFilter};

let filter = EnvFilter::try_from_env("MY_CUSTOM_FILTER_ENV_VAR")?
    // Set the base level when not matched by other directives to WARN.
    .add_directive(LevelFilter::WARN.into())
    // Set the max level for `my_crate::my_mod` to DEBUG, overriding
    // any directives parsed from the env variable.
    .add_directive("my_crate::my_mod=debug".parse()?);

json_subscriber::fmt()
    .with_env_filter(filter)
    .try_init()?;
Source

pub fn with_max_level( self, filter: impl Into<LevelFilter>, ) -> SubscriberBuilder<W, T, LevelFilter>

Sets the maximum verbosity level that will be enabled by the collector.

If the max level has already been set, or a EnvFilter was added by with_env_filter, this replaces that configuration with the new maximum level.

§Examples

Enable up to the DEBUG verbosity level:

use tracing_subscriber::fmt;
use tracing::Level;

fmt()
    .with_max_level(Level::DEBUG)
    .init();

This collector won’t record any spans or events!

use tracing_subscriber::{fmt, filter::LevelFilter};

let subscriber = fmt()
    .with_max_level(LevelFilter::OFF)
    .finish();
Source

pub fn with_filter_reloading<S>(self) -> SubscriberBuilder<W, T, Layer<F, S>>

Available on crate feature env-filter only.

Configures the collector being built to allow filter reloading at runtime.

The returned builder will have a reload_handle method, which returns a reload::Handle that may be used to set a new filter value.

For example:

use tracing::Level;

let builder = json_subscriber::fmt()
     // Set a max level filter on the collector
    .with_max_level(Level::INFO)
    .with_filter_reloading();

// Get a handle for modifying the collector's max level filter.
let handle = builder.reload_handle();

// Finish building the collector, and set it as the default.
builder.finish().init();

// Currently, the max level is INFO, so this event will be disabled.
tracing::debug!("this is not recorded!");

// Use the handle to set a new max level filter.
// (this returns an error if the collector has been dropped, which shouldn't
// happen in this example.)
handle.reload(Level::DEBUG).expect("the collector should still exist");

// Now, the max level is INFO, so this event will be recorded.
tracing::debug!("this is recorded!");
Source§

impl<W, T, F, S> SubscriberBuilder<W, T, Layer<F, S>>

Source

pub fn reload_handle(&self) -> Handle<F, S>

Returns a Handle that may be used to reload the constructed collector’s filter.

Trait Implementations§

Source§

impl Default for SubscriberBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<W, T, F> Freeze for SubscriberBuilder<W, T, F>
where W: Freeze, T: Freeze, F: Freeze,

§

impl<W, T, F> RefUnwindSafe for SubscriberBuilder<W, T, F>

§

impl<W, T, F> Send for SubscriberBuilder<W, T, F>
where W: Send, T: Send, F: Send,

§

impl<W, T, F> Sync for SubscriberBuilder<W, T, F>
where W: Sync, T: Sync, F: Sync,

§

impl<W, T, F> Unpin for SubscriberBuilder<W, T, F>
where W: Unpin, T: Unpin, F: Unpin,

§

impl<W, T, F> UnwindSafe for SubscriberBuilder<W, T, F>
where W: UnwindSafe, T: UnwindSafe, F: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more