# rust-happy-log 😊
[](https://crates.io/crates/rust-happy-log)
[](https://docs.rs/rust-happy-log)
[](LICENSE)
一个美观、高性能的 Rust 日志库,支持控制台和文件输出。
## ✨ 特性
- 🎨 **美观输出**: 支持彩色输出和 emoji 图标,让日志更易读
- 🚀 **高性能**: 异步写入,主线程零阻塞,使用 crossbeam-channel 实现高效队列
- 🔒 **线程安全**: 全局单例模式,多线程环境下安全使用
- 📁 **文件轮转**: 支持按文件大小自动轮转,自动管理备份文件
- ⚙️ **灵活配置**: Builder 模式配置,简单易用
- 📍 **位置信息**: 自动记录文件名和行号,快速定位问题
- 🎯 **零依赖侵入**: 全局单例,各模块无需传递 Logger 实例
## 📦 安装
在 `Cargo.toml` 中添加依赖:
```toml
[dependencies]
rust-happy-log = "0.1"
```
## 🚀 快速开始
### 基础使用
```rust
use rust_happy_log::{LoggerBuilder, Level, info, warn, error};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 初始化全局日志器(仅需一次)
LoggerBuilder::new()
.level(Level::Info)
.console(true)
.init()?;
// 在任意位置使用便捷宏
info!("应用启动");
warn!("这是一个警告: {}", "注意");
error!("发生错误: {}", "错误信息");
Ok(())
}
```
### 输出到文件
```rust
use rust_happy_log::{LoggerBuilder, Level, info};
fn main() -> Result<(), Box<dyn std::error::Error>> {
LoggerBuilder::new()
.level(Level::Info)
.console(true) // 控制台输出
.file("logs/app.log") // 文件输出
.file_max_size(10 * 1024 * 1024) // 10MB 轮转
.file_max_backups(5) // 保留 5 个备份
.init()?;
info!("日志将同时输出到控制台和文件");
Ok(())
}
```
### 多模块使用(全局单例)
```rust
use rust_happy_log::{LoggerBuilder, Level, info, error};
// 模块 A
mod auth {
use rust_happy_log::info;
pub fn login(user: &str) {
info!("用户 {} 登录", user); // 直接使用,无需传递 Logger
}
}
// 模块 B
mod database {
use rust_happy_log::error;
pub fn query(sql: &str) {
error!("查询失败: {}", sql); // 直接使用全局实例
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 仅在主函数初始化一次
LoggerBuilder::new()
.level(Level::Info)
.console(true)
.init()?;
// 各模块直接使用,无需传递 Logger 实例
auth::login("admin");
database::query("SELECT * FROM users");
Ok(())
}
```
## 🎨 输出示例
控制台彩色输出效果:
```
[2025-10-06 15:24:30.123] 🔍 TRACE 这是追踪级别日志
[2025-10-06 15:24:30.124] 🐛 DEBUG 这是调试级别日志
[2025-10-06 15:24:30.125] ℹ️ INFO 应用启动成功
[2025-10-06 15:24:30.126] ⚠️ WARN 这是一个警告
[2025-10-06 15:24:30.127] ❌ ERROR 发生错误
```
## ⚙️ 配置选项
### 完整配置示例
```rust
use rust_happy_log::{LoggerBuilder, Level};
LoggerBuilder::new()
// 日志级别
.level(Level::Debug)
// 控制台配置
.console(true) // 启用控制台输出
.console_color(true) // 彩色输出
.console_emoji(true) // emoji 图标
.console_thread(true) // 显示线程 ID
.console_location(true) // 显示文件位置(文件名:行号)
// 文件配置
.file("logs/app.log") // 日志文件路径
.file_max_size(10 * 1024 * 1024) // 最大 10MB
.file_max_backups(5) // 保留 5 个备份文件
.init()
.expect("日志初始化失败");
```
### 日志级别
- `Level::Trace`: 最详细的日志,用于追踪程序执行
- `Level::Debug`: 调试信息
- `Level::Info`: 一般信息(默认)
- `Level::Warn`: 警告信息
- `Level::Error`: 错误信息
### 运行时调整级别
```rust
use rust_happy_log::{Logger, Level};
// 获取全局 Logger 并调整级别
if let Ok(logger) = Logger::global() {
logger.set_level(Level::Debug);
}
```
## 📝 可用宏
```rust
trace!("追踪信息: {}", value);
debug!("调试信息: {}", value);
info!("一般信息: {}", value);
warn!("警告信息: {}", value);
error!("错误信息: {}", value);
```
所有宏都支持 `format!` 风格的格式化。
## 🏗️ 架构设计
### 核心特性
1. **全局单例**: 使用 `once_cell::OnceCell` 实现线程安全的全局实例
2. **异步写入**: 后台线程处理日志写入,主线程零阻塞
3. **高性能队列**: 使用 `crossbeam-channel` 实现无锁队列
4. **优雅关闭**: 程序退出时自动刷新所有日志
### 性能优化
- 使用有界队列(容量 10000)避免内存无限增长
- 非阻塞发送,队列满时丢弃日志而不阻塞主线程
- 使用 `parking_lot::Mutex` 替代标准库 Mutex,性能更优
- 文件写入使用 `BufWriter` 缓冲,减少系统调用
## 📚 示例
查看 `examples/` 目录获取更多示例:
```bash
# 基础使用
cargo run --example basic
# 文件输出
cargo run --example file_output
# 多模块使用
cargo run --example multi_module
# 高级配置
cargo run --example advanced
```
## 🔧 开发
```bash
# 检查代码
cargo check
# 运行测试
cargo test
# 格式化代码
cargo fmt
# Clippy 检查
cargo clippy
# 构建文档
cargo doc --open
```
## 📄 许可证
本项目采用双许可证:
- MIT License
- Apache License 2.0
您可以选择其中任意一个许可证使用本项目。
## 🤝 贡献
欢迎提交 Issue 和 Pull Request!
## 📮 联系方式
- 仓库: https://github.com/yourusername/rust-happy-log
- 问题反馈: https://github.com/yourusername/rust-happy-log/issues
## 🙏 致谢
本项目使用了以下优秀的 Rust 库:
- `colored` - 彩色终端输出
- `crossbeam-channel` - 高性能并发通道
- `once_cell` - 单例模式支持
- `thiserror` - 错误处理
- `chrono` - 时间处理
- `parking_lot` - 高性能同步原语