Skip to content

Instantly share code, notes, and snippets.

@zty5678
Last active March 23, 2024 07:39
Show Gist options
  • Save zty5678/f92230f20999965e2ee5a49ec391a6d4 to your computer and use it in GitHub Desktop.
Save zty5678/f92230f20999965e2ee5a49ec391a6d4 to your computer and use it in GitHub Desktop.
Rust Log Utils, use to print line number in console output. (Only tested in RustRover )
mod utils_log;
fn main() {
utils_log::log("hello world");
}
use std::env;
use std::path::Path;
use backtrace::{Backtrace, BacktraceFrame, BacktraceSymbol};
use chrono::{DateTime, Local};
fn previous_symbol(level: u32) -> Option<BacktraceSymbol> {
let (trace, curr_file, curr_line) = (Backtrace::new(), file!(), line!());
let frames = trace.frames();
frames.iter()
.flat_map(BacktraceFrame::symbols)
.skip_while(|s| s.filename().map(|p| !p.ends_with(curr_file)).unwrap_or(true)
|| s.lineno() != Some(curr_line))
.nth(1 + level as usize).cloned()
}
pub(crate) fn log(msg: &str) {
let sym = previous_symbol(1);
if let (Some(line_no), Some(file_name)) =
(sym.as_ref().and_then(BacktraceSymbol::lineno), sym.as_ref().and_then(BacktraceSymbol::filename)) {
if let Ok(curr_dir) = env::current_dir() {
if let Some(relative_path) = Path::new(&file_name)
.strip_prefix(&curr_dir)
.ok()
.and_then(|p| p.to_str())
{
let current_time: DateTime<Local> = Local::now();
let formatted_time = current_time.format("%Y-%m-%d %H:%M:%S%.3f").to_string();
println!(" --> {:}:{}][{}]:{}", relative_path, line_no, formatted_time, msg);
return;
}
}
}
}
@zty5678
Copy link
Author

zty5678 commented Mar 23, 2024

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment