Skip to content

Commit

Permalink
look, ma, i got tracin
Browse files Browse the repository at this point in the history
  • Loading branch information
nothendev committed Oct 1, 2023
1 parent efd54f5 commit fadab48
Show file tree
Hide file tree
Showing 10 changed files with 169 additions and 11 deletions.
14 changes: 13 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ bevy = { version = "0.11.2", features = ["multi-threaded"], default-features = f
rayon = "1"
itertools = "0"
flate2 = "1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
2 changes: 1 addition & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ edition = "2021"

[dependencies]
oxcr_protocol.workspace = true
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
tracing-subscriber.workspace = true
itertools.workspace = true
1 change: 1 addition & 0 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![feature(iterator_try_collect, try_blocks)]

#[allow(dead_code, unused_imports)]
mod cli;
pub use cli::{flag_list, Extra, FlagName};
mod error;
Expand Down
4 changes: 4 additions & 0 deletions protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ miette = { version = "5.10.0", features = ["fancy"] }
indexmap = { version = "2.0.0", features = ["serde"] }

flate2.workspace = true
tracing-subscriber.workspace = true
nu-ansi-term = "0.49.0"

itertools.workspace = true
2 changes: 2 additions & 0 deletions protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

pub mod error;
pub mod executor;
pub mod logging;
pub mod model;
pub mod nbt;
pub mod nsfr;
Expand All @@ -29,6 +30,7 @@ pub mod serde {
}
pub use indexmap;
pub use miette;
pub use nu_ansi_term as ansi;
pub use tracing;

pub async fn rwlock_set<T: 'static>(rwlock: &RwLock<T>, value: T) {
Expand Down
127 changes: 127 additions & 0 deletions protocol/src/logging.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
use std::collections::HashMap;

use itertools::Itertools;
use nu_ansi_term::{Color, Style};
use tracing::{field::Field, Level};
use tracing_subscriber::Layer;

pub struct CraftLayer;

impl<S: tracing::Subscriber> Layer<S> for CraftLayer {
fn on_event(
&self,
event: &tracing::Event<'_>,
_context: tracing_subscriber::layer::Context<'_, S>,
) {
// inspiration taken from pnpm
let level = Color::Black
.on(match *event.metadata().level() {
Level::INFO => Color::Green,
Level::WARN => Color::Yellow,
Level::ERROR => Color::Red,
Level::DEBUG => Color::Blue,
Level::TRACE => Color::Purple,
})
.bold()
.paint(format!(" {} ", event.metadata().level().as_str()));

let pad_level = " ".repeat(5 - event.metadata().level().as_str().len());

let mut visitor = CraftVisitor {
message: None,
other_fields: HashMap::new(),
};

event.record(&mut visitor);

let message = visitor
.message
.as_deref()
.map(|message| format!(" {message}"))
.unwrap_or(String::new());

// should look like
// field = value field2 = value2
let other_fields = if visitor.other_fields.is_empty() {
String::new()
} else {
let padding = " ".repeat(
// max length of level
7
// space after level before target
+ 1,
);
let real = visitor
.other_fields
.iter()
.map(|(key, value)| {
format!(
"{} = {value}",
Style::default().dimmed().italic().paint(key)
)
})
.collect::<Vec<String>>()
.join(&format!("\n{padding}"));
format!("\n{padding}{real}",)
};

let target = event
.metadata()
.target()
.split("::")
.map(|module| Color::Cyan.paint(module).to_string())
.intersperse_with(|| Color::LightRed.paint("::").to_string())
.collect::<String>();

println!("{level}{pad_level} {target}{message} {other_fields}");
}
}

struct CraftVisitor {
message: Option<String>,
other_fields: HashMap<String, String>,
}

impl CraftVisitor {
fn record(&mut self, field: &Field, value: String) {
if field.name() == "message" {
let _ = self.message.insert(value);
} else {
let _ = self.other_fields.insert(field.name().to_owned(), value);
}
}
}

impl tracing::field::Visit for CraftVisitor {
fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
self.record(field, value.to_string())
}

fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
self.record(field, value.to_string())
}

fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
self.record(field, value.to_string())
}

fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
self.record(field, value.to_string())
}

fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
self.record(field, value.to_string())
}

fn record_error(
&mut self,
field: &tracing::field::Field,
value: &(dyn std::error::Error + 'static),
) {
self.record(field, value.to_string())
}

fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
self.record(field, format!("{value:?}"))
}
}
6 changes: 3 additions & 3 deletions protocol/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -962,7 +962,7 @@ impl Compression for Zlib {
BytesMut::new().writer(),
flate2::Compression::default(),
);
enc.write_all(&data);
enc.write_all(&data)?;
Ok(enc.finish()?.into_inner().freeze())
}

Expand Down Expand Up @@ -991,9 +991,9 @@ impl Compression for Zlib {

let mut bmut = BytesMut::new();
thing.serialize_to(&mut bmut)?;
enc.write_all(&bmut);
enc.write_all(&bmut)?;

enc.finish();
enc.finish()?;

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ oxcr_cli.workspace = true
tokio.workspace = true
bevy.workspace = true
tracing.workspace = true
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-subscriber.workspace = true
21 changes: 16 additions & 5 deletions server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use model::DifficultySetting;
use oxcr_protocol::{
executor::{TaskContext, TokioTasksRuntime},
indexmap::IndexMap,
logging::CraftLayer,
miette::{self, IntoDiagnostic, Report},
model::{
chat::{self, *},
Expand Down Expand Up @@ -36,7 +37,9 @@ use oxcr_protocol::{
use std::{net::SocketAddr, sync::Arc};
use tokio::{net::TcpListener, sync::mpsc};
use tracing::instrument;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::{
prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt, EnvFilter,
};

use crate::{
error::Error,
Expand Down Expand Up @@ -367,16 +370,24 @@ fn init_registries(

#[tokio::main]
async fn main() -> Result<(), Report> {
tracing_subscriber::fmt()
.pretty()
.with_env_filter(EnvFilter::from_env("OXCR_LOG"))
tracing_subscriber::registry()
.with(EnvFilter::from_env("OXCR_LOG"))
.with(CraftLayer)
.init();

miette::set_panic_hook();

let cli = cli::Cli::parse_args()?;

debug!("{cli:#?}");
debug!(?cli);

trace!(
r#"Hello, dude with OXCR_LOG=trace.
I see you have some intention of getting more info out of this program.
Please be aware that if you do not turn OXCR_LOG=trace down
to something like =debug or =info, your log files might explode.
That was my warning, now I wish you good luck debugging your issue."#
);

let tcp = tokio::net::TcpListener::bind(("127.0.0.1", cli.port))
.await
Expand Down

0 comments on commit fadab48

Please sign in to comment.