Search code examples
rustrust-macros

Get println! to prefix given string with current time


println!("Start") // Start
printlnt!("Start"); // [231209_14:00:00] Start

How could I make a macro like the above?


Solution

  • You can define a macro as below

    macro_rules! printlnt {
        ($($arg:tt)*) => {
            println!("[{}] {}", chrono::Local::now().format("%y%m%d_%H:%M:%S"), $($arg)*);
        };
    }