Rust-Loguru
A flexible and efficient logging library for Rust inspired by Python's Loguru. Designed to provide an intuitive, powerful logging experience while maintaining Rust's performance characteristics.
Features
- Multiple log levels: TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL
- Thread-safe global logger: Safe to use in multi-threaded applications
- Extensible handler system: Console, file, and custom handlers
- Configurable log formatting: Customize how log messages are displayed
- Support for metadata in log records: Add structured data to log messages
- Convenient logging macros: Easy to use macros for all log levels
- File rotation: Automatic file rotation based on size with retention policies
- Colorized output: Colorful console output for better readability
- Source location capture: Automatically capture file, line, and module information
- Ergonomic error handling and context helpers: Extension traits, error chain, panic hook, and macros
Installation
Add this to your Cargo.toml
:
[]
= "0.1.15" # Or Newer version
Performance Benchmarks
Basic Logging (single-message overhead at DEBUG, INFO, ERROR levels)
Concurrent Logging (INFO-level with 2, 4, 8, 16 threads)
High-Volume Logging (bulk emit of 100, 1 000, 10 000 messages)
File-Rotation (write and rotate files)
Key Findings:
-
Standard Logging Performance:
- slog shows exceptional performance for most standard operations (3-6 ns)
- loguru consistently performs well (160-180 ns), significantly faster than log and tracing
- log and tracing show higher execution times (400-650 ns)
-
Concurrent Logging:
- All libraries show scaling patterns with more threads, but slog maintains the best performance
- loguru shows excellent multithreading efficiency, ranking 2nd consistently
-
File Rotation:
- slog is fastest at 7.08ms
- tracing follows at 16.65ms
- log4rs at 32.73ms
- loguru is slowest at 48.05ms
-
High Volume Logging:
- For very high volumes (10,000 elements), slog maintains exceptional performance
- loguru handles large volumes significantly better than both log and tracing
Quick Start
use ;
use ConsoleHandler;
use Arc;
use RwLock;
Macro Usage Examples
Rust-Loguru provides a rich set of macros for ergonomic and powerful logging, context, and error handling. Here are some advanced macro usages:
Context Macros
use ;
push_context!;
set_context!;
let user = get_context!;
println!;
pop_context!;
Scope Macros
use ;
// Simple scope guard for timing and indentation
let _guard = scope!;
// Log entering and exiting a scope with timing
let _scope = scoped_info!;
Error Integration Macros
use ;
let err = "something went wrong";
log_error!;
log_error!;
log_error_with_context!;
let res: = Err;
let _ = try_log!;
let opt: = None;
let _ = try_log!;
Compile-time Level Filtering
use ;
let result = log_if_enabled!;
Structured Data in Level Macros
use info_kv;
info_kv!;
Core Concepts
Log Levels
Rust-Loguru supports the following log levels, in order of increasing severity:
- TRACE: Very detailed information, typically only useful for debugging specific issues
- DEBUG: Detailed information useful for debugging
- INFO: General information about the application's operation
- SUCCESS: Successful operations (similar to INFO but indicates success)
- WARNING: Potential issues that don't prevent the application from working
- ERROR: Errors that prevent specific operations from working
- CRITICAL: Critical errors that may lead to application failure
Handlers
Handlers determine where log messages are sent. Rust-Loguru comes with:
- ConsoleHandler: Outputs logs to stdout or stderr
- FileHandler: Writes logs to a file with optional rotation
- NullHandler: Discards all logs (useful for testing)
Creating a Console Handler
use ConsoleHandler;
use LogLevel;
// Output to stderr with INFO level
let handler = stderr
.with_colors
.with_pattern;
Creating a File Handler
use FileHandler;
use LogLevel;
use Path;
// Write to a file with rotation at 10MB and keep 5 old files
let handler = new.unwrap
.with_rotation
.with_retention
.with_colors;
Logging with Metadata
You can add structured metadata to log records:
use ;
// Using the Record API directly
let record = new
.with_metadata
.with_metadata;
log;
// Or using the macro
log_with_metadata!;
Customizing Formatters
Customize how logs are formatted:
use Formatter;
let formatter = new
.with_colors
.with_timestamp
.with_level
.with_module
.with_location
.with_pattern;
Configuration Presets
Use built-in configuration presets:
use LoggerConfig;
// Development configuration with detailed logging
let config = development;
// Production configuration with minimal logging
let config = production;
Using TOML Configuration Files
You can load logger configuration from a TOML file or string. This is useful for externalizing configuration and making it easy to adjust logging without code changes.
Example TOML file (loguru_config.toml
):
= "Debug"
= true
= false
= "[TOML] {level} {message}"
Loading from a TOML file:
use LoggerConfigBuilder;
let config = new
.from_toml_file
.unwrap
.build;
Loading from a TOML string:
use LoggerConfigBuilder;
let toml = r#"
level = "Info"
use_colors = true
"#;
let config = new
.from_toml_str
.unwrap
.build;
Precedence:
- Values set via builder methods or environment variables will override those loaded from TOML.
- Supported TOML keys:
level
,capture_source
,use_colors
,format
.
Scopes and Timed Execution
Rust-Loguru provides a ScopeGuard
utility for measuring the duration of code blocks and managing indentation for nested scopes. This is useful for profiling, debugging, and structured logging of code execution.
use ScopeGuard;
use thread;
use Duration;
- Indentation is managed per-thread and resets after panics.
- Use
ScopeGuard::elapsed()
to get the time spent in a scope. - Indentation increases with nested scopes and decreases on exit.
Error Handling Utilities
Rust-Loguru provides ergonomic helpers for error handling, context, and panic reporting.
Extension Traits for Result
and Option
use ;
Error Chain Extraction
use ;
Panic Hook Installation
use install_panic_hook;
Source Location and Error Logging Macros
use ;
Advanced Usage
Creating Custom Handlers
Implement the Handler
trait to create custom handlers:
use Handler;
use LogLevel;
use Record;
use Formatter;
Structured Logging with JSON
Use the structured data capability:
use ;
use json;
let record = new
.with_structured_data
.unwrap;
log;
Advanced Context Usage
Rust-Loguru supports structured, thread-local, and async-propagatable context for logs. This allows you to automatically attach metadata (like user IDs, request IDs, etc.) to every log line in a given scope or async task.
use ;
Async Context Propagation
You can propagate context across async tasks:
use context;
use thread;
let mut ctx = new;
ctx.insert;
push_context;
let arc_ctx = propagate_context_for_async;
spawn;
Performance Considerations
- Log records below the configured level are filtered out early for minimal overhead
- File handlers use buffered I/O for efficient disk operations
- Consider using appropriate log levels in production to minimize overhead
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Integration Features
Rust-Loguru provides an integration
module for compatibility and middleware with other logging systems and frameworks. This module is designed for advanced use cases where you want to:
- Use Rust-Loguru as the backend for the
log
crate - Integrate with async runtimes (e.g., spawn log flushing tasks in tokio)
- Add middleware for web frameworks (e.g., request/response logging)
Log Crate Compatibility
Rust-Loguru can act as the backend for the log
crate. This allows you to use the standard log
macros (log::info!
, log::warn!
, etc.) and have them routed through Rust-Loguru.
use log_compat;
use info;
Async Runtime Integration (Tokio)
Rust-Loguru can integrate with async runtimes like Tokio to spawn background tasks for log management.
Requires the tokio
feature.
use async_runtime;
async
Framework Middleware (Web Frameworks)
use middleware;
Test Utilities
Rust-Loguru provides a set of test utilities to help you capture logs, assert on log output, and use mock loggers in your tests. These are available in the rust_loguru::test_utils
module.
Log Capture
You can capture log records during tests and inspect them:
use LogCapture;
use ;
let capture = new;
let record = new;
capture.handle;
assert!;
assert!;
Assertion Macros
Rust-Loguru provides macros to assert that a log capture contains a message or a log level:
use LogCapture;
use ;
use ;
let capture = new;
let record = new;
capture.handle;
assert_log_contains!;
assert_log_level!;
Mock Logger
A mock logger is provided for testing code that expects a logger:
use MockLogger;
use ;
let logger = new;
let record = new;
logger.log;
assert!;
Temporary Log Level Adjustment
You can temporarily set the log level for a logger in a test:
use TempLogLevel;
use ;
let mut logger = MyLogger ;
assert_eq!;
TODO / Roadmap
The following is the prioritized development plan:
-
Performance Improvements
- Adopt the Zero Overhead of
slog
to bring down the performance numbers down
- Adopt the Zero Overhead of
-
File Handler Enhancements
- Time-based rotation (daily, hourly, etc.)
- Retention policies (max age, max files, cleanup of old logs)
- File permissions (configurable on creation)
- Async file writing (true async I/O, not just async logging queue)
-
Configuration System Upgrades
- Environment variable overrides (e.g.,
RUST_LOGURU_LEVEL=debug
) - File-based configuration (TOML/YAML/JSON config loading)
- Preset configurations (easy-to-use, opinionated defaults for common scenarios)
- Environment variable overrides (e.g.,
-
Integration & Extensibility
- Async runtime integration (fully implement tokio/async-std support, e.g., log flushing, context propagation)
- Framework middleware (request/response logging for actix, axum, etc.)
- Network/HTTP/in-memory handlers (implement or stub with clear errors/documentation)
-
Advanced Handler Features
- Batching for all handlers (not just file, but also network, etc.)
- Handler-specific filtering (allow each handler to filter by level, target, etc.)
- Compression options (support for gzip, zip, etc. for rotated files)
-
Context & Scope Improvements
- Panic/exception capture in scopes (log panics with context and stack trace)
- Async scope support (ensure scopes work seamlessly with async/await)
-
Documentation & Cleanup
- Remove legacy files (e.g.,
src/formatter.rs
) - Document stubbed/unimplemented features (make it clear what is and isn't available)
- Update README and module docs to reflect new features and usage patterns
- Remove legacy files (e.g.,
-
Optional/Bonus
- File permission control for log files
- Support for emojis/symbols in all formatters
- More built-in format templates
- Integration with external services (CloudWatch, Elasticsearch, etc.)
Contributions to any of these areas are welcome! See the issues tracker for more details or to discuss implementation approaches.
License
This project is licensed under MIT of:
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)