3 stable releases
1.0.2 | Dec 6, 2024 |
---|
#153 in Debugging
372 downloads per month
31KB
557 lines
Loggix ๐ฆ
A powerful structured logger for Rust, inspired by Logrus. Loggix combines structured logging with Rust's safety and performance guarantees.
Features
- ๐ฏ Seven log levels: Trace, Debug, Info, Warning, Error, Fatal, and Panic
- ๐ Structured logging with fields
- ๐จ Beautiful terminal output with colors (when TTY is attached)
- ๐ JSON formatter for machine processing
- ๐ช Extensible hook system
- ๐ Thread-safe by default
- ๐ Global and local logger instances
- ๐ Customizable formatters
- ๐ฎ Full control over output (any type implementing
std::io::Write
)
Quick Start
Add to your Cargo.toml
:
[dependencies]
loggix = "1.0.2"
Basic Logging
use loggix::{info, debug, warn, error};
fn main() {
debug!("Debug message");
info!("Info message");
warn!("Warning message");
error!("Error message");
}
Structured Logging
use loggix::with_fields;
fn main() {
// Log with structured fields
with_fields!(
"user_id" => "12345",
"action" => "login",
"ip" => "192.168.1.1"
)
.info("User login successful")
.unwrap();
}
JSON Output
use loggix::{Logger, JSONFormatter, with_fields};
fn main() {
let logger = Logger::new()
.formatter(JSONFormatter::new().pretty(true))
.build();
with_fields!(
"transaction_id" => "tx-9876",
"amount" => 150.50,
"currency" => "USD"
)
.info("Payment processed")
.unwrap();
}
Output:
{
"timestamp": "2024-12-06T20:30:21.103Z",
"level": "info",
"message": "Payment processed",
"transaction_id": "tx-9876",
"amount": 150.50,
"currency": "USD"
}
Error Handling
use loggix::with_error;
use std::fs::File;
fn main() {
let result = File::open("non_existent.txt");
if let Err(error) = result {
with_error(&error)
.error("Failed to open file")
.unwrap();
}
}
Custom Logger Instance
use loggix::{Logger, Level, TextFormatter};
fn main() {
let logger = Logger::new()
.level(Level::Debug)
.formatter(TextFormatter::new()
.timestamp_format("%Y-%m-%d %H:%M:%S")
.colors(true)
.build())
.build();
logger.with_fields(Default::default())
.with_field("component", "auth")
.info("Authentication successful")
.unwrap();
}
Advanced Usage
Custom Formatters
Implement the Formatter
trait to create your own log format:
use loggix::{Formatter, Entry};
use std::error::Error;
struct MyFormatter;
impl Formatter for MyFormatter {
fn format(&self, entry: &Entry) -> Result<Vec<u8>, Box<dyn Error>> {
let mut output = Vec::new();
// Format the log entry however you want
write!(&mut output, "MY-LOG: {} - {}", entry.level, entry.message)?;
Ok(output)
}
}
Custom Hooks
Implement the Hook
trait to process log entries:
use loggix::{Hook, Entry, Level};
struct MetricsHook;
impl Hook for MetricsHook {
fn fire(&self, entry: &Entry) -> Result<(), Box<dyn Error>> {
// Send metrics to your metrics system
if entry.level == Level::Error {
// Record error metrics
}
Ok(())
}
fn levels(&self) -> Vec<Level> {
vec![Level::Error, Level::Fatal]
}
}
Examples
Check out the examples directory for more detailed examples:
Performance
Loggix is designed for high performance while maintaining flexibility. Here are some key performance characteristics:
Benchmark Results
Basic logging: 813.57 ns/iter
Structured logging: 1.34 ยตs/iter (with 2 fields)
Multiple fields: 2.23 ยตs/iter (with 4 fields)
Key performance features:
- Zero-allocation logging paths for common use cases
- Efficient field storage using pre-allocated hashmaps
- Lock-free architecture where possible
- Linear scaling with number of fields
- Thread-safe by default with minimal overhead
Running Benchmarks
Run the benchmarks yourself with:
cargo bench
The benchmarks use Criterion.rs for statistical analysis and reliable measurements.
Thread Safety
Loggix is designed to be thread-safe by default. All logging operations are atomic and can be safely used across multiple threads. The library uses Arc
and Mutex
internally to protect shared state.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Roadmap
Here are the planned features and enhancements for Loggix:
Data Store Integration
- ๐๏ธ Database Support
- PostgreSQL integration for persistent logging
- MongoDB support for document-based logging
- ClickHouse for high-performance analytics
- TimescaleDB for time-series data
Message Queue & Streaming
- ๐ Apache Kafka Integration
- Real-time log streaming
- Multi-topic support
- Partitioning strategies
- ๐ Redis Streams Support
- ๐ RabbitMQ Integration
Search & Analytics
- ๐ Elasticsearch Integration
- Full-text search capabilities
- Log aggregation and analysis
- Custom mapping templates
- ๐ OpenSearch Support
Advanced Features
- ๐น Trading Systems Support
- High-frequency trading logs
- Order execution tracking
- Market data logging
- ๐ Enhanced Security
- Log encryption at rest
- Audit trail capabilities
- GDPR compliance features
- ๐ Distributed Systems
- Distributed tracing integration
- OpenTelemetry support
- Correlation ID tracking
Performance & Scaling
- ๐ High-Performance Mode
- Zero-copy logging
- Lock-free implementation
- Memory-mapped files
- ๐ฏ Load Balancing
- Dynamic log routing
- Automatic failover
- Horizontal scaling
Monitoring & Alerting
- ๐ก Real-time Monitoring
- Custom metrics export
- Prometheus integration
- Health check endpoints
- โก Alert System
- Configurable thresholds
- Multiple notification channels
- Alert aggregation
Additional Features
- ๐ Log Rotation
- Size-based rotation
- Time-based rotation
- Compression support
- ๐จ Advanced Formatting
- Custom template engine
- Multiple output formats
- Dynamic field masking
- ๐งช Testing Tools
- Mock logger implementation
- Assertion helpers
- Performance benchmarks
These features are in various stages of planning and development. Contributions and feedback are welcome!
License
This project is licensed under the MIT License - see the LICENSE file for details.
Dependencies
~1.7โ9MB
~85K SLoC