Struct json_subscriber::JsonLayer

source ·
pub struct JsonLayer<S = Registry, W = fn() -> Stdout> { /* private fields */ }
Expand description

Layer that implements logging JSON to a configured output. This is a lower-level API that may change a bit in next versions.

See fmt::Layer for an alternative especially if you’re migrating from tracing_subscriber.

Implementations§

source§

impl<S> JsonLayer<S>
where S: Subscriber + for<'lookup> LookupSpan<'lookup>,

source

pub fn stdout() -> JsonLayer<S, fn() -> Stdout>

Creates an empty JsonLayer which will output logs to stdout.

source

pub fn stderr() -> JsonLayer<S, fn() -> Stderr>

Creates an empty JsonLayer which will output logs to stderr.

source

pub fn new<W>(make_writer: W) -> JsonLayer<S, W>
where W: for<'writer> MakeWriter<'writer> + 'static,

Creates an empty JsonLayer which will output logs to the configured Writer.

source§

impl<S, W> JsonLayer<S, W>
where S: Subscriber + for<'lookup> LookupSpan<'lookup>,

source

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

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

§Examples

Using stderr rather than stdout:

use std::io;
use tracing_subscriber::fmt;

let fmt_subscriber = fmt::subscriber()
    .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
let subscriber = fmt::subscriber().with_writer(non_blocking(std::io::stderr()));
let (subscriber, reload_handle) = reload::JsonLayer::new(subscriber);
info!("This will be logged to stderr");
reload_handle.modify(|subscriber| *subscriber.writer_mut() = non_blocking(std::io::stdout()));
info!("This will be logged to stdout");
source

pub fn with_test_writer(self) -> JsonLayer<S, TestWriter>

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:

use std::io;
use tracing_subscriber::fmt;

let fmt_subscriber = fmt::subscriber()
    .with_test_writer();
source

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

Sets whether to write errors from FormatEvent to the writer. Defaults to true.

By default, fmt::JsonLayer will write any FormatEvent-internal errors to the writer. These errors are unlikely and will only occur if there is a bug in the FormatEvent implementation or its dependencies.

If writing to the writer fails, the error message is printed to stderr as a fallback.

source

pub fn map_writer<W2>(self, f: impl FnOnce(W) -> W2) -> JsonLayer<S, W2>
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::{self, writer::MakeWriterExt};

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

pub fn add_static_field( &mut self, key: impl Into<Cow<'static, str>>, value: Value, )

Adds a new static field with a given key to the output.

§Examples

Print hostname in each log:

let mut layer = json_subscriber::JsonLayer::stdout();
layer.add_static_field(
    "hostname",
    serde_json::json!({
        "hostname": get_hostname(),
    }),
);

registry().with(layer);
source

pub fn remove_field(&mut self, key: impl Into<Cow<'static, str>>)

Removes a field that was inserted to the output.

§Examples

Add a field and then remove it:

let mut layer = json_subscriber::JsonLayer::stdout();
layer.add_static_field(
    "deleteMe",
    serde_json::json!("accident"),
);
layer.remove_field("deleteMe");

registry().with(layer);
source

pub fn serialize_extension<Ext: Serialize + 'static>( &mut self, key: impl Into<Cow<'static, str>>, )

Adds a field with a given key to the output. The value will be serialized JSON of the provided extension. Other Layers may add these extensions to the span.

The serialization happens every time a log line is emitted so if the extension changes, the latest version will be emitted.

If the extension is not found, nothing is added to the output.

§Examples
struct FooLayer;

#[derive(Serialize)]
struct Foo(String);

impl<S: Subscriber + for<'lookup> LookupSpan<'lookup>> Layer<S> for FooLayer {
    fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
        let span = ctx.span(id).unwrap();
        let mut extensions = span.extensions_mut();
        let foo = Foo("hello".to_owned());
        extensions.insert(foo);
    }
}

let foo_layer = FooLayer;

let mut layer = json_subscriber::JsonLayer::stdout();
layer.serialize_extension::<Foo>("foo");

registry().with(foo_layer).with(layer);
source

pub fn add_from_extension_ref<Ext, Fun, Res>( &mut self, key: impl Into<Cow<'static, str>>, mapper: Fun, )
where Ext: 'static, for<'a> Fun: Fn(&'a Ext) -> Option<&'a Res> + Send + Sync + 'a, Res: Serialize,

Adds a field with a given key to the output. The user-provided closure can transform the extension and return reference to any serializable structure.

The mapping and serialization happens every time a log line is emitted so if the extension changes, the latest version will be emitted.

If the extension is not found, or the mapping returns None, nothing is added to the output.

Use Self::add_from_extension if you cannot return a reference.

§Examples
struct FooLayer;

#[derive(Serialize)]
struct Foo(String);

impl<S: Subscriber + for<'lookup> LookupSpan<'lookup>> Layer<S> for FooLayer {
    fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
        let span = ctx.span(id).unwrap();
        let mut extensions = span.extensions_mut();
        let foo = Foo("hello".to_owned());
        extensions.insert(foo);
    }
}

let foo_layer = FooLayer;

let mut layer = json_subscriber::JsonLayer::stdout();
layer.add_from_extension_ref::<Foo, _, _>("foo", |foo| Some(&foo.0));

registry().with(foo_layer).with(layer);
source

pub fn add_from_extension<Ext, Fun, Res>( &mut self, key: impl Into<Cow<'static, str>>, mapper: Fun, )
where Ext: 'static, for<'a> Fun: Fn(&'a Ext) -> Option<Res> + Send + Sync + 'a, Res: Serialize,

Adds a field with a given key to the output. The user-provided closure can transform the extension and return any serializable structure.

The mapping and serialization happens every time a log line is emitted so if the extension changes, the latest version will be emitted.

If the extension is not found, or the mapping returns None, nothing is added to the output.

Use Self::add_from_extension_ref if you want to return a reference to data in the extension.

§Examples
struct FooLayer;

#[derive(Serialize)]
struct Foo(String);

impl<S: Subscriber + for<'lookup> LookupSpan<'lookup>> Layer<S> for FooLayer {
    fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
        let span = ctx.span(id).unwrap();
        let mut extensions = span.extensions_mut();
        let foo = Foo("hello".to_owned());
        extensions.insert(foo);
    }
}

let foo_layer = FooLayer;

let mut layer = json_subscriber::JsonLayer::stdout();
layer.add_from_extension::<Foo, _, _>("foo", |foo| foo.0.parse::<u64>().ok());

registry().with(foo_layer).with(layer);
source

pub fn flatten_event(&mut self, flatten_event: bool) -> &mut Self

Print all event fields in an object with the key fields if the argument is false, or flatten all the fields on top level of the JSON log line if set to true.

If set to true, it is the user’s responsibility to make sure that the field names will not clash with other defined fields. If they clash, invalid JSON with multiple fields with the same key may be generated.

source

pub fn with_current_span(&mut self, display_current_span: bool) -> &mut Self

Sets whether or not the log line will include the current span in formatted events. If set to true, it will be printed with the key span.

source

pub fn with_span_list(&mut self, display_span_list: bool) -> &mut Self

Sets whether or not the formatter will include a list (from root to leaf) of all currently entered spans in formatted events. If set to true, it will be printed with the key spans.

source

pub fn with_timer<T: FormatTime + Send + Sync + 'static>( &mut self, timer: T, ) -> &mut Self

Use the given timer for log message timestamps with the timestamp key.

See the time module for the provided timer implementations.

source

pub fn without_time(&mut self) -> &mut Self

Clears the timestamp fields.

source

pub fn with_target(&mut self, display_target: bool) -> &mut Self

Sets whether or not an event’s target is displayed. It will use the target key if so.

source

pub fn with_file(&mut self, display_filename: bool) -> &mut Self

Sets whether or not an event’s source code file path is displayed. It will use the file key if so.

source

pub fn with_line_number(&mut self, display_line_number: bool) -> &mut Self

Sets whether or not an event’s source code line number is displayed. It will use the line_number key if so.

source

pub fn with_level(&mut self, display_level: bool) -> &mut Self

Sets whether or not an event’s level is displayed. It will use the level key if so.

source

pub fn with_thread_names(&mut self, display_thread_name: bool) -> &mut Self

Sets whether or not the name of the current thread is displayed when formatting events. It will use the threadName key if so.

source

pub fn with_thread_ids(&mut self, display_thread_id: bool) -> &mut Self

Sets whether or not the thread ID of the current thread is displayed when formatting events. It will use the threadId key if so.

source

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

Available on crate feature opentelemetry only.

Sets whether or not OpenTelemetry trace ID and span ID is displayed when formatting events. It will use the openTelemetry key if so and the value will be an object with traceId and spanId fields, each being a string.

Trait Implementations§

source§

impl<S, W> Layer<S> for JsonLayer<S, W>
where S: Subscriber + for<'lookup> LookupSpan<'lookup>, W: for<'writer> MakeWriter<'writer> + 'static,

source§

fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>)

Notifies this layer that a new span was constructed with the given Attributes and Id.
source§

fn on_record(&self, id: &Id, values: &Record<'_>, ctx: Context<'_, S>)

Notifies this layer that a span with the given Id recorded the given values.
source§

fn on_enter(&self, _id: &Id, _ctx: Context<'_, S>)

Notifies this layer that a span with the given ID was entered.
source§

fn on_exit(&self, _id: &Id, _ctx: Context<'_, S>)

Notifies this layer that the span with the given ID was exited.
source§

fn on_close(&self, _id: Id, _ctx: Context<'_, S>)

Notifies this layer that the span with the given ID has been closed.
source§

fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>)

Notifies this layer that an event has occurred.
source§

fn on_register_dispatch(&self, subscriber: &Dispatch)

Performs late initialization when installing this layer as a Subscriber. Read more
source§

fn on_layer(&mut self, subscriber: &mut S)

Performs late initialization when attaching a Layer to a Subscriber. Read more
source§

fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest

Registers a new callsite with this layer, returning whether or not the layer is interested in being notified about the callsite, similarly to Subscriber::register_callsite. Read more
source§

fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool

Returns true if this layer is interested in a span or event with the given metadata in the current Context, similarly to Subscriber::enabled. Read more
source§

fn on_follows_from(&self, _span: &Id, _follows: &Id, _ctx: Context<'_, S>)

Notifies this layer that a span with the ID span recorded that it follows from the span with the ID follows.
source§

fn event_enabled(&self, _event: &Event<'_>, _ctx: Context<'_, S>) -> bool

Called before on_event, to determine if on_event should be called.
source§

fn on_id_change(&self, _old: &Id, _new: &Id, _ctx: Context<'_, S>)

Notifies this layer that a span ID has been cloned, and that the subscriber returned a different ID.
source§

fn and_then<L>(self, layer: L) -> Layered<L, Self, S>
where L: Layer<S>, Self: Sized,

Composes this layer around the given Layer, returning a Layered struct implementing Layer. Read more
source§

fn with_subscriber(self, inner: S) -> Layered<Self, S>
where Self: Sized,

Composes this Layer with the given Subscriber, returning a Layered struct that implements Subscriber. Read more
source§

fn with_filter<F>(self, filter: F) -> Filtered<Self, F, S>
where Self: Sized, F: Filter<S>,

Available on crate features registry and std only.
Combines self with a Filter, returning a Filtered layer. Read more

Auto Trait Implementations§

§

impl<S, W> Freeze for JsonLayer<S, W>
where W: Freeze,

§

impl<S = Registry, W = fn() -> Stdout> !RefUnwindSafe for JsonLayer<S, W>

§

impl<S, W> Send for JsonLayer<S, W>
where W: Send,

§

impl<S, W> Sync for JsonLayer<S, W>
where W: Sync,

§

impl<S, W> Unpin for JsonLayer<S, W>
where W: Unpin,

§

impl<S = Registry, W = fn() -> Stdout> !UnwindSafe for JsonLayer<S, W>

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> 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>,

§

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>,

§

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