#logging #structured #log-structured #log #json #log-level #logrus

loggix

A powerful, structured logging library for Rust inspired by Logrus. Features thread-safe logging, structured fields, custom formatters, and beautiful terminal output.

3 stable releases

1.0.2 Dec 6, 2024

#153 in Debugging

Download history 275/week @ 2024-12-02 97/week @ 2024-12-09

372 downloads per month

MIT license

31KB
557 lines

Loggix ๐Ÿฆ€

Crates.io Documentation License Crates.io

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