Hello,
I am quite new to Rust and Programming in general.
My Goal is to create a Library for logging for practice and because none of the once I have found really have the Features I want to have.
I want to have Macros like info!(), warn!(), error!(), debug!(), trace!()
and you can Configure the Logger in a Config file.
In this Config file you can define if for example the info!() macro should write to Stdout or to a File Descriptor, but I cannot get it to work how would I make this?
It should look like this but I am not sure if this is even possible
macro_rules! info {
() => {
println!("{}-INFO:", get_ts())
};
($($arg:tt)*) => {{
writeln!(FD, "{}-INFO: {}",get_ts(), format_args!($($arg)*));
}};
}
EDIT:
I have found a solution which works for me, it may be not the best one but ok.
I have created a trait which impls File and Stdout
trait MyWriter: Write {}
impl MyWriter for io::Stdout {}
impl MyWriter for File {}
and then just created a function which will return my anything which impls my trait
fn get_fd() -> impl MyWriter {
let fd = std::fs::File::create("test.txt").unwrap();
fd
}
and I use it in the marcro like this
#[macro_export]
macro_rules! info {
() => {
println!("{}-INFO:", get_ts())
};
($($arg:tt)*) => {{
let mut fd = get_fd();
let _ = writeln!(fd, "{}-INFO: {}",get_ts(), format_args!($($arg)*));
}};
}
If anybody has a better Idea I am open but this works for me