Last active
March 23, 2024 07:39
-
-
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 )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod utils_log; | |
fn main() { | |
utils_log::log("hello world"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Author
zty5678
commented
Mar 23, 2024
![image](https://private-user-images.githubusercontent.com/2247076/316225866-47f90be4-8e0f-4726-adac-31cc1658a2c7.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MTkxNjAyODgsIm5iZiI6MTcxOTE1OTk4OCwicGF0aCI6Ii8yMjQ3MDc2LzMxNjIyNTg2Ni00N2Y5MGJlNC04ZTBmLTQ3MjYtYWRhYy0zMWNjMTY1OGEyYzcucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI0MDYyMyUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNDA2MjNUMTYyNjI4WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9M2Q2NTE5YzMwNzIxYTM5ZGI0N2VlOWNlNThiZTgyODFmZDBiYmVjYmM5YTcyMzQyZDU3YTYyODYwYjFlNjdiMiZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QmYWN0b3JfaWQ9MCZrZXlfaWQ9MCZyZXBvX2lkPTAifQ.GSGkjvD9WumDwzU_t4JSRRtzOmVTt4YjVoPzSG2qH2U)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment