Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for tracing-subscriber #31

Merged
merged 5 commits into from
Mar 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ travis-ci = { repository = "gin66/tui-logger" }
log = "0.4"
chrono = "0.4"
tui = { version = "0.19", default-features = false }
tracing = {version = "0.1.37", optional = true}
tracing-subscriber = {version = "0.3", optional = true}
lazy_static = "1.0"
fxhash = "0.2"
parking_lot = "0.12"
Expand All @@ -29,3 +31,5 @@ env_logger = "0.10.0"

[features]
default = ["slog"]
tracing-support = ["tracing", "tracing-subscriber"]

15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,12 @@
//! `tui-logger` provides a TuiSlogDrain which implements `slog::Drain` and will route all records
//! it receives to the `tui-logger` widget
//!
//! //! ## `tracing-subscriber` support
//!
//! `tui-logger` provides a TuiTracingSubscriberLayer which implements
//! `tracing_subscriber::Layer` and will collect all events
//! it receives to the `tui-logger` widget
//!
//! ## Custom filtering
//! ```rust
//! #[macro_use]
Expand Down Expand Up @@ -172,10 +178,14 @@ use tui::widgets::{Block, Borders, Widget};
mod circular;
#[cfg(feature = "slog")]
mod slog;
#[cfg(feature = "tracing-support")]
mod tracing_subscriber;

pub use crate::circular::CircularBuffer;
#[cfg(feature = "slog")]
pub use crate::slog::TuiSlogDrain;
#[cfg(feature = "tracing-support")]
pub use crate::tracing_subscriber::TuiTracingSubscriberLayer;

struct ExtLogRecord {
timestamp: DateTime<Local>,
Expand Down Expand Up @@ -396,6 +406,11 @@ pub fn slog_drain() -> TuiSlogDrain {
TuiSlogDrain
}

#[cfg(feature = "tracing-support")]
pub fn tracing_subscriber_layer() -> TuiTracingSubscriberLayer {
TuiTracingSubscriberLayer
}

/// Set the depth of the hot buffer in order to avoid message loss.
/// This is effective only after a call to move_events()
pub fn set_hot_buffer_depth(depth: usize) {
Expand Down
107 changes: 107 additions & 0 deletions src/tracing_subscriber.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
//! `tracing-subscriber` support for `tui-logger`

use super::TUI_LOGGER;
use log::{self, Log, Record};
use std::collections::HashMap;
use std::fmt;
use tracing_subscriber::Layer;

#[derive(Default)]
struct ToStringVisitor<'a>(HashMap<&'a str, String>);

impl fmt::Display for ToStringVisitor<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0
.iter()
.try_for_each(|(k, v)| -> fmt::Result { write!(f, " {}: {}", k, v) })
}
}

impl<'a> tracing::field::Visit for ToStringVisitor<'a> {
fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
self.0
.insert(field.name(), format_args!("{}", value).to_string());
}

fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
self.0
.insert(field.name(), format_args!("{}", value).to_string());
}

fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
self.0
.insert(field.name(), format_args!("{}", value).to_string());
}

fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
self.0
.insert(field.name(), format_args!("{}", value).to_string());
}

fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
self.0
.insert(field.name(), format_args!("{}", value).to_string());
}

fn record_error(
&mut self,
field: &tracing::field::Field,
value: &(dyn std::error::Error + 'static),
) {
self.0
.insert(field.name(), format_args!("{}", value).to_string());
}

fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
self.0
.insert(field.name(), format_args!("{:?}", value).to_string());
}
}

#[allow(clippy::needless_doctest_main)]
/// tracing-subscriber-compatible layer that feeds messages to `tui-logger`.
///
/// ## Basic usage:
/// ```
/// //use tui_logger;
///
/// fn main() {
/// tracing_subscriber::registry()
/// .with(tui_logger::tracing_subscriber_layer())
/// .init();
/// info!(log, "Logging via tracing works!");
/// }
pub struct TuiTracingSubscriberLayer;

impl<S> Layer<S> for TuiTracingSubscriberLayer
where
S: tracing::Subscriber,
{
fn on_event(
&self,
event: &tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let mut visitor = ToStringVisitor::default();
event.record(&mut visitor);

let level = match *event.metadata().level() {
tracing::Level::ERROR => log::Level::Error,
tracing::Level::WARN => log::Level::Warn,
tracing::Level::INFO => log::Level::Info,
tracing::Level::DEBUG => log::Level::Debug,
tracing::Level::TRACE => log::Level::Trace,
};

TUI_LOGGER.log(
&Record::builder()
.args(format_args!("{}", visitor))
.level(level)
.target(event.metadata().target())
.file(event.metadata().file())
.line(event.metadata().line())
.module_path(event.metadata().module_path())
.build(),
);
}
}