feat: polish the OpaqueError get_span_trace function looks

This commit is contained in:
Tamipes 2026-05-29 11:07:59 +02:00
parent 1bce912a1a
commit 0e2afd0772
3 changed files with 24 additions and 15 deletions

View file

@ -189,7 +189,7 @@ impl MinecraftAPI<Server> for McApi {
drop(guard);
if let Err(err) = server.stop().await {
tracing::error!(
trace = err.get_span_trace(),
trace = %err.print_span_trace(),
err = err.context,
msg = "failed to stop server"
);

View file

@ -61,26 +61,26 @@ async fn main() {
match e.level {
tracing::Level::ERROR => tracing::error!(
// addr = format!("{}:{}", addr.ip().to_string(), addr.port().to_string()),
trace = format!("{}", e.get_span_trace()),
trace = %e.print_span_trace(),
err = format!("{}", e.context),
"Client disconnected"
),
tracing::Level::WARN => tracing::warn!(
// addr = format!("{}:{}", addr.ip().to_string(), addr.port().to_string()),
trace = format!("{}", e.get_span_trace()),
trace = %e.print_span_trace(),
err = format!("{}", e.context),
"Client disconnected"
),
tracing::Level::INFO => tracing::info!(
// addr = format!("{}:{}", addr.ip().to_string(), addr.port().to_string()),
trace = format!("{}", e.get_span_trace()),
trace = %e.print_span_trace(),
err = format!("{}", e.context),
"Client disconnected"
),
_ => {
tracing::error!(
// addr = format!("{}:{}", addr.ip().to_string(), addr.port().to_string()),
trace = format!("{}", e.get_span_trace()),
trace = %e.print_span_trace(),
err = format!("{}", e.context),
actual_level = ?e.level,
"Client disconnected (bad level)"

View file

@ -1,4 +1,7 @@
use std::{error::Error, fmt};
use std::{
error::Error,
fmt::{self, Debug},
};
use tracing::Level;
use tracing_error::SpanTrace;
@ -50,7 +53,7 @@ impl OpaqueError {
kind: Some(kind.to_string()),
}
}
pub fn get_span_trace(&self) -> String {
pub fn print_span_trace(&self) -> FancyTrace {
let mut vec: Vec<(&str, String)> = Vec::new();
self.span_trace.with_spans(|metadata, _fields| {
@ -64,16 +67,14 @@ impl OpaqueError {
}
acc.push_str(x.0);
if !x.1.is_empty() {
acc.push_str("{");
acc.push_str(&x.1);
acc.push_str("}");
}
acc
});
match String::from_utf8(strip_ansi_escapes::strip(str.clone())) {
Ok(x) => x,
Err(_) => str,
}
FancyTrace { str }
}
pub fn set_level(mut self, lvl: Level) -> Self {
self.level = lvl;
@ -86,6 +87,14 @@ impl OpaqueError {
}
}
}
pub struct FancyTrace {
str: String,
}
impl fmt::Display for FancyTrace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.str)
}
}
impl From<String> for OpaqueError {
fn from(value: String) -> Self {