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

new: Add custom tracing/meitte handlers. #16

Merged
merged 2 commits into from
Apr 8, 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
342 changes: 294 additions & 48 deletions Cargo.lock

Large diffs are not rendered by default.

9 changes: 4 additions & 5 deletions crates/framework/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,15 @@ starbase_events = { version = "0.1.0", path = "../events" }
starbase_macros = { version = "0.1.1", path = "../macros" }
starbase_styles = { version = "0.1.0", path = "../styles", features = ["theme"] }
async-trait = { workspace = true }
miette = { workspace = true }
chrono = { version = "0.4.24", default-features = false, features = ["clock", "std"] }
miette = { workspace = true, features = ["fancy"] }
num_cpus = "1.15.0"
relative-path = { workspace = true }
rustc-hash = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["tracing"] }
tracing = { workspace = true, optional = true }
tracing-subscriber = { version = "0.3.16", optional = true }
tracing-subscriber = { version = "0.3.16", optional = true, default-features = false, features = ["fmt"] }

[features]
default = ["panic", "tracing"]
panic = ["miette/fancy"]
default = ["tracing"]
tracing = ["dep:tracing", "dep:tracing-subscriber", "starbase_macros/tracing"]
16 changes: 2 additions & 14 deletions crates/framework/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::resources::{ResourceInstance, ResourceManager, Resources};
use crate::states::{StateInstance, StateManager, States};
use crate::system::{BoxedSystem, CallbackSystem, System, SystemFunc};
use miette::IntoDiagnostic;
use starbase_styles::theme::create_graphical_theme;
use std::any::Any;
use std::mem;
use std::sync::Arc;
Expand Down Expand Up @@ -57,20 +56,9 @@ impl App {
}

pub fn setup_hooks() {
#[cfg(feature = "panic")]
miette::set_panic_hook();

crate::diagnostic::set_miette_hooks();
#[cfg(feature = "tracing")]
tracing_subscriber::fmt::init();

miette::set_hook(Box::new(|_| {
Box::new(
miette::MietteHandlerOpts::new()
.graphical_theme(create_graphical_theme())
.build(),
)
}))
.unwrap();
crate::tracing::set_tracing_subscriber();
}

/// Add a system function that runs during the startup phase.
Expand Down
15 changes: 15 additions & 0 deletions crates/framework/src/diagnostic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use starbase_styles::theme::create_graphical_theme;

pub fn set_miette_hooks() {
miette::set_panic_hook();

miette::set_hook(Box::new(|_| {
Box::new(
miette::MietteHandlerOpts::new()
.with_cause_chain()
.graphical_theme(create_graphical_theme())
.build(),
)
}))
.unwrap();
}
6 changes: 4 additions & 2 deletions crates/framework/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
mod app;
mod app_state;
mod diagnostic;
mod emitters;
mod instance;
mod resources;
mod states;
mod system;

#[cfg(feature = "tracing")]
mod tracing;

pub use app::*;
pub use app_state::AppState;
pub use emitters::*;
Expand All @@ -14,8 +18,6 @@ pub use starbase_macros::*;
pub use states::*;
pub use system::*;

pub use relative_path::{RelativePath, RelativePathBuf};

pub mod diagnose {
pub use miette::*;
pub use thiserror::Error;
Expand Down
155 changes: 155 additions & 0 deletions crates/framework/src/tracing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
use chrono::{Local, Timelike};
use starbase_styles::{color, format_style_tags};
use std::env;
use std::sync::atomic::{AtomicU8, Ordering};
use tracing::{field::Visit, Level, Metadata, Subscriber};
use tracing_subscriber::{
field::RecordFields,
fmt::{self, time::FormatTime, FormatEvent, FormatFields, SubscriberBuilder},
registry::LookupSpan,
};

static LAST_HOUR: AtomicU8 = AtomicU8::new(0);

struct FieldVisitor<'writer> {
is_testing: bool,
printed_delimiter: bool,
writer: fmt::format::Writer<'writer>,
}

impl<'writer> Visit for FieldVisitor<'writer> {
fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
if field.name() == "message" {
self.record_debug(field, &format_args!("{}", value))
} else {
self.record_debug(field, &value)
}
}

fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
if field.name() == "message" {
write!(
self.writer,
" {}",
format_style_tags(format!("{:?}", value))
)
.unwrap()
} else if !self.is_testing {
if !self.printed_delimiter {
write!(self.writer, " {}", color::muted("|")).unwrap();
self.printed_delimiter = true;
}

write!(
self.writer,
" {}",
color::muted(format!("{}={:?}", field.name(), value))
)
.unwrap()
}
}
}

struct EventFormatter {
is_testing: bool,
}

impl EventFormatter {
pub fn new() -> Self {
Self {
is_testing: env::var("STARBASE_TEST").is_ok(),
}
}
}

impl FormatTime for EventFormatter {
fn format_time(&self, writer: &mut fmt::format::Writer<'_>) -> std::fmt::Result {
if self.is_testing {
return write!(writer, "YYYY-MM-DD");
}

let mut date_format = "%Y-%m-%d %H:%M:%S";
let current_timestamp = Local::now();
let current_hour = current_timestamp.hour() as u8;

if current_hour == LAST_HOUR.load(Ordering::Acquire) {
date_format = "%H:%M:%S";
} else {
LAST_HOUR.store(current_hour, Ordering::Release);
}

write!(
writer,
"{}",
color::muted(current_timestamp.format(date_format).to_string()),
)
}
}

impl<'writer> FormatFields<'writer> for EventFormatter {
fn format_fields<R: RecordFields>(
&self,
writer: fmt::format::Writer<'writer>,
fields: R,
) -> std::fmt::Result {
let mut visitor = FieldVisitor {
is_testing: self.is_testing,
printed_delimiter: false,
writer,
};

fields.record(&mut visitor);

Ok(())
}
}

impl<S, N> FormatEvent<S, N> for EventFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &fmt::FmtContext<'_, S, N>,
mut writer: fmt::format::Writer<'_>,
event: &tracing::Event<'_>,
) -> std::fmt::Result {
let meta: &Metadata = event.metadata();
let level: &Level = meta.level();

// [level timestamp]
write!(writer, "{}", color::muted("["))?;
write!(writer, "{} ", color::muted(level.as_str()))?;
self.format_time(&mut writer)?;
write!(writer, "{}", color::muted("]"))?;

// target:spans...
write!(writer, " {}", color::log_target(meta.target()))?;

if let Some(scope) = ctx.event_scope() {
for span in scope.from_root() {
write!(
writer,
"{}{}",
color::muted(":"),
color::muted_light(span.name())
)?;
}
}

// message ...field=value
self.format_fields(writer.by_ref(), event)?;

writeln!(writer)
}
}

pub fn set_tracing_subscriber() {
let subscriber = SubscriberBuilder::default()
.event_format(EventFormatter::new())
.finish();

// Ignore the error incase the subscriber is already set
let _ = tracing::subscriber::set_global_default(subscriber);
}
6 changes: 3 additions & 3 deletions crates/framework/tests/instance_macros_test.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(dead_code, unused_must_use)]

use starbase::RelativePathBuf;
// use starbase::RelativePathBuf;
use starbase_macros::*;
use std::path::PathBuf;

Expand All @@ -27,8 +27,8 @@ enum State4 {
#[derive(Debug, State)]
struct StatePath(PathBuf);

#[derive(Debug, State)]
struct StateRelPath(RelativePathBuf);
// #[derive(Debug, State)]
// struct StateRelPath(RelativePathBuf);

// RESOURCE

Expand Down
4 changes: 2 additions & 2 deletions crates/macros/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ pub fn macro_impl(item: TokenStream) -> TokenStream {
}),
"RelativePathBuf" => Some(quote! {
#[automatically_derived]
impl AsRef<starbase::RelativePath> for #struct_name {
fn as_ref(&self) -> &starbase::RelativePath {
impl AsRef<relative_path::RelativePath> for #struct_name {
fn as_ref(&self) -> &relative_path::RelativePath {
&self.0
}
}
Expand Down
8 changes: 7 additions & 1 deletion crates/styles/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@ static STYLE_TOKEN: Lazy<Mutex<Regex>> =

#[inline]
pub fn format_style_tags<T: AsRef<str>>(value: T) -> String {
let value = value.as_ref();

if !value.contains('<') {
return value.to_string();
}

String::from(
STYLE_TOKEN
.lock()
.unwrap()
.replace_all(value.as_ref(), |caps: &Captures| {
.replace_all(value, |caps: &Captures| {
let token = caps.get(1).map_or("", |m| m.as_str());
let inner = caps.get(2).map_or("", |m| m.as_str());

Expand Down
40 changes: 24 additions & 16 deletions crates/styles/src/theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,30 @@ use miette::{GraphicalTheme, ThemeStyles};
pub fn create_graphical_theme() -> GraphicalTheme {
let mut theme = GraphicalTheme::unicode();

theme.styles = ThemeStyles {
error: color::style(Color::Red as u8),
warning: color::style(Color::Yellow as u8),
advice: color::style(Color::Teal as u8),
help: color::style(Color::Purple as u8),
link: color::style(Color::Blue as u8),
linum: color::style(Color::GrayLight as u8),
highlights: vec![
color::style(Color::Green as u8),
color::style(Color::Teal as u8),
color::style(Color::Blue as u8),
color::style(Color::Purple as u8),
color::style(Color::Pink as u8),
color::style(Color::Red as u8),
],
};
if let Some(supports) = supports_color::on(supports_color::Stream::Stderr) {
if supports.has_256 || supports.has_16m {
theme.styles = ThemeStyles {
error: color::style(Color::Red as u8),
warning: color::style(Color::Yellow as u8),
advice: color::style(Color::Teal as u8),
help: color::style(Color::Purple as u8),
link: color::style(Color::Blue as u8),
linum: color::style(Color::GrayLight as u8),
highlights: vec![
color::style(Color::Green as u8),
color::style(Color::Teal as u8),
color::style(Color::Blue as u8),
color::style(Color::Purple as u8),
color::style(Color::Pink as u8),
color::style(Color::Red as u8),
],
};
} else {
theme.styles = ThemeStyles::ansi();
}
} else {
theme.styles = ThemeStyles::none();
}

theme
}
8 changes: 6 additions & 2 deletions crates/test-app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async fn start_two(states: States, _resources: Resources, em: EmitterMut<TestEve

#[system]
async fn analyze_one(state: StateMut<TestState>, em: EmitterRef<TestEvent>) {
info!(val = state.0, "analyze");
info!(val = state.0, "analyze <file>foo.bar</file>");
**state = "mutated".to_string();

let event = TestEvent(50);
Expand All @@ -68,7 +68,11 @@ async fn missing_file() {

#[system]
async fn fail() {
if std::env::var("FAIL").is_ok() {
if let Ok(fail) = std::env::var("FAIL") {
if fail == "panic" {
panic!("This paniced!");
}

warn!("fail");
return Err(AppError::Test)?;
}
Expand Down