| Crates.io | log_init |
| lib.rs | log_init |
| version | 0.1.34 |
| created_at | 2025-08-29 03:51:00.675504+00 |
| updated_at | 2025-12-12 22:26:54.441227+00 |
| description | Smart logging initialization with automatic backend detection / 智能日志初始化与自动后端检测 |
| homepage | https://github.com/js0-site/rust/tree/dev/log_init |
| repository | https://github.com/js0-site/rust.git |
| max_upload_size | |
| id | 1815306 |
| size | 61,069 |
log_init is a Rust logging initialization library that provides intelligent backend selection and cross-platform compatibility. It automatically detects the runtime environment and chooses the optimal logging backend - systemd journald on Linux systems or stdout with customizable formatting on other platforms.
RUST_LOG environment variableAdd to your Cargo.toml:
[dependencies]
log_init = "0.1"
log = "0.4"
use log::{info, warn, error};
fn main() {
log_init::init();
info!("Application started");
warn!("This is a warning");
error!("Something went wrong");
}
use log::info;
fn main() {
log_init::init();
info!(
user_id = 42,
action = "login",
duration_ms = 150.5;
"User authentication successful"
);
}
# Set log level
export RUST_LOG=debug
# Run your application
cargo run
[dependencies]
log_init = { version = "0.1", features = ["systemd"] }
Available features:
stdout (default): Enable stdout logging backendsystemd: Enable systemd journald support on Linuxinit()Initializes the global logger with automatic backend detection.
pub fn init()
Behavior:
INVOCATION_ID environment variable is presentlevel_color(level: Level) -> ColoredStringReturns a colored string representation of the log level.
pub fn level_color(level: Level) -> ColoredString
TextCustomizable text formatter for stdout logging.
pub struct Text {
pub color: bool,
}
Methods:
default(): Creates formatter with automatic color detection based on terminal capabilityformat(): Formats log records with timestamps, file locations, and structured dataTZGlobal timezone static for consistent timestamp formatting.
pub static TZ: jiff::tz::TimeZone
graph TD
A[Application] --> B[log_init::init]
B --> C{Platform Detection}
C -->|Linux + systemd| D[journald Backend]
C -->|Other/Fallback| E[stdout Backend]
D --> F[logforth Framework]
E --> G[Text Formatter]
G --> H[Color Detection]
G --> I[Timezone Handling]
F --> J[Environment Filter]
J --> K[Log Output]
init() orchestrates the entire initialization processlayout::Text handles stdout formatting and color managementkv::Kv processes structured logging key-value pairslog_init/
├── src/
│ ├── lib.rs # Main library entry point and initialization logic
│ ├── kv.rs # Key-value pair processing for structured logging
│ └── layout/
│ ├── mod.rs # Layout module exports
│ └── text.rs # Text formatter implementation
├── tests/
│ └── main.rs # Comprehensive test suite
├── readme/
│ ├── en.md # English documentation
│ └── zh.md # Chinese documentation
├── Cargo.toml # Project configuration and dependencies
└── test.sh # Test execution script
# Run all tests with output
./test.sh
# Or use cargo directly
cargo test --all-features -- --nocapture
cargo doc --all-features --open
# Test stdout backend only
cargo test --no-default-features --features stdout
# Test with systemd support (Linux only)
cargo test --features systemd
The evolution of logging in systems programming reflects the broader development of observability practices. Early Unix systems relied on simple file-based logging through syslog, introduced in the 1980s. The concept of structured logging gained prominence with the rise of distributed systems in the 2000s.
systemd's journald, introduced in 2011, revolutionized Linux logging by providing binary log storage, automatic metadata collection, and integration with the init system. This represented a significant departure from traditional text-based logs, offering better performance and richer context.
The Rust ecosystem's approach to logging, exemplified by the log crate's facade pattern, emerged from lessons learned in other languages about the importance of abstraction between logging interfaces and implementations. This design allows libraries to remain agnostic about logging backends while applications retain full control over log destination and formatting.
log_init bridges these historical approaches by providing intelligent backend selection - leveraging modern systemd capabilities where available while maintaining compatibility with traditional stdout-based logging for broader platform support.
This project is an open-source component of js0.site ⋅ Refactoring the Internet Plan.
We are redefining the development paradigm of the Internet in a componentized way. Welcome to follow us:
log_init是Rust日志初始化库,提供智能后端选择和跨平台兼容性。自动检测运行环境并选择最优日志后端 - Linux系统上使用systemd journald,其他平台使用可定制格式的stdout输出。
RUST_LOG环境变量配置日志级别添加到Cargo.toml:
[dependencies]
log_init = "0.1"
log = "0.4"
use log::{info, warn, error};
fn main() {
log_init::init();
info!("应用程序启动");
warn!("这是警告信息");
error!("发生错误");
}
use log::info;
fn main() {
log_init::init();
info!(
user_id = 42,
action = "login",
duration_ms = 150.5;
"用户认证成功"
);
}
# 设置日志级别
export RUST_LOG=debug
# 运行应用程序
cargo run
[dependencies]
log_init = { version = "0.1", features = ["systemd"] }
可用特性:
stdout (默认): 启用stdout日志后端systemd: 在Linux上启用systemd journald支持init()使用自动后端检测初始化全局日志器。
pub fn init()
行为:
INVOCATION_ID环境变量时使用journaldlevel_color(level: Level) -> ColoredString返回日志级别的彩色字符串表示。
pub fn level_color(level: Level) -> ColoredString
Textstdout日志的可定制文本格式化器。
pub struct Text {
pub color: bool,
}
方法:
default(): 基于终端能力自动检测颜色创建格式化器format(): 格式化日志记录,包含时间戳、文件位置和结构化数据TZ用于一致时间戳格式化的全局时区静态变量。
pub static TZ: jiff::tz::TimeZone
graph TD
A[应用程序] --> B[log_init::init]
B --> C{平台检测}
C -->|Linux + systemd| D[journald后端]
C -->|其他/回退| E[stdout后端]
D --> F[logforth框架]
E --> G[文本格式化器]
G --> H[颜色检测]
G --> I[时区处理]
F --> J[环境过滤器]
J --> K[日志输出]
init()协调整个初始化过程layout::Text处理stdout格式化和颜色管理kv::Kv处理结构化日志键值对log_init/
├── src/
│ ├── lib.rs # 主库入口点和初始化逻辑
│ ├── kv.rs # 结构化日志键值对处理
│ └── layout/
│ ├── mod.rs # 布局模块导出
│ └── text.rs # 文本格式化器实现
├── tests/
│ └── main.rs # 综合测试套件
├── readme/
│ ├── en.md # 英文文档
│ └── zh.md # 中文文档
├── Cargo.toml # 项目配置和依赖
└── test.sh # 测试执行脚本
# 运行所有测试并显示输出
./test.sh
# 或直接使用cargo
cargo test --all-features -- --nocapture
cargo doc --all-features --open
# 仅测试stdout后端
cargo test --no-default-features --features stdout
# 测试systemd支持 (仅Linux)
cargo test --features systemd
系统编程中日志记录的演进反映了可观测性实践的广泛发展。早期Unix系统依赖通过syslog进行简单的基于文件的日志记录,该技术在1980年代引入。结构化日志的概念随着2000年代分布式系统的兴起而获得重视。
systemd的journald于2011年引入,通过提供二进制日志存储、自动元数据收集和与init系统的集成,彻底改变了Linux日志记录。这代表了对传统基于文本日志的重大突破,提供了更好的性能和更丰富的上下文。
Rust生态系统的日志记录方法,以log crate的门面模式为例,源于其他语言中关于日志接口和实现之间抽象重要性的经验教训。这种设计允许库对日志后端保持不可知,同时应用程序保留对日志目标和格式化的完全控制。
log_init通过提供智能后端选择来桥接这些历史方法 - 在可用时利用现代systemd功能,同时保持与传统基于stdout的日志记录的兼容性以获得更广泛的平台支持。
本项目为 js0.site ⋅ 重构互联网计划 的开源组件。
我们正在以组件化的方式重新定义互联网的开发范式,欢迎关注: