#debugging #print #macro

log_macro

仅打印变量名和值的宏(从发布构建中移除)

7 个版本

0.1.6 2023 年 8 月 21 日
0.1.5 2023 年 8 月 20 日

#473开发工具

Download history 18/week @ 2024-06-29 143/week @ 2024-07-27

每月 161 次下载

MIT 许可证

8KB

log_macro crates.io

宏以优雅的方式打印变量(从发布构建中移除)

安装

cargo add log_macro

使用

将此添加到文件顶部

#[macro_use]
extern crate log_macro;

可能的用途和输出

// print string only
log!("hello"); // -> hello

// print variable
let animals = vec!["cat", "dog"];
log!(animals); // -> animals: ["cat", "dog"]

// print multiple variables
let animals = vec!["cat", "dog"];
let fish = vec!["salmon", "tuna"];
log!(animals, fish);
// each variable logged on new line
// -> animals: ["cat", "dog"]
// -> fish: ["salmon", "tuna"]

变量将以绿色显示以突出显示。

实现

导出的宏代码如下

#[macro_export]
macro_rules! log {
    // Single literal string case
    ( $val:expr $(,)? ) => {{
        #[cfg(debug_assertions)]
        {
            if ::std::stringify!($val).starts_with("\"") {
                // Remove quotes for string literals
                ::std::eprintln!("{}", ::std::stringify!($val).trim_matches('\"'));
            } else {
                // Print using a reference to avoid moving the value
                ::std::eprintln!("\x1B[32m{}\x1B[0m: {:?}", ::std::stringify!($val), &$val);
            }
        }
    }};

    // Multiple variables case
    ( $($val:expr),+ $(,)? ) => {{
        #[cfg(debug_assertions)]
        {
            $(
                $crate::log!($val);
            )+
        }
    }};
}

运行

将在 src/lib.rs 中运行测试。

cargo watch -q -- sh -c "tput reset && cargo test -q --lib"

贡献

要完成的任务概述在 现有问题 和以下 任务 中(按优先级排序)。

如果您的问题/想法不在其中,请 打开新问题开始讨论

欢迎任何改进代码/文档的 PR。 ✨

加入 Discord 进行更多关于此仓库和其他仓库的深入讨论。

任务

♥️

在GitHub上支持或查看其他项目

MIT Twitter

无运行时依赖