lumelog

Crates.iolumelog
lib.rslumelog
version0.1.9
created_at2024-12-07 19:04:46.344537+00
updated_at2025-10-19 00:02:08.761207+00
descriptionA lightweight, flexible, and configurable logging library for Rust, with support for runtime configuration and build-mode detection.
homepage
repositoryhttps://github.com/LinearDev/lumelog
max_upload_size
id1475820
size169,131
Eugene Kyrylenko (Eugen263)

documentation

https://docs.rs/lumelog/latest/lumelog/

README

🌟 LumeLog

Crates.io Documentation License: MIT OR Apache-2.0

LumeLog is a lightweight, flexible, and configurable logging library for Rust. It supports different log levels, runtime configuration, and styled log outputs, making it suitable for both development and production environments.

Key Highlights:

  • 🎨 Styled Console Output with color-coded log levels
  • πŸ“ File Logging support with JSON and text formats plus automatic directory creation
  • βš™οΈ Runtime Configuration without recompilation
  • πŸ”’ Thread-Safe with OnceCell for global configuration
  • πŸ§ͺ Comprehensive Test Suite with 40+ integration tests across multiple test files
  • πŸ› οΈ Developer-Friendly with included Makefile for common tasks
  • πŸ—‚οΈ Smart Directory Management with automatic nested directory creation

πŸ“š Table of Contents

Features

  • Log Levels: Supports ERROR, WARN, INFO, DEBUG, and TRACE.
  • Styled Output: Provides color-coded logs for enhanced readability.
  • File Logging: Optionally logs messages to a file in text or JSON format.
  • Runtime Configuration: Configure logging behavior without recompiling.
  • Build Mode Detection: Automatically adjusts logging for debug or release builds.

Installation

Add lumelog to your Cargo.toml:

[dependencies]
lumelog = "0.1.6"

Then, include it in your code:

use lumelog::{info, warn, error, ConfigBuilder, LogLevel};

Quick Start

Here’s a basic example to get started:

use lumelog::{info, error, warn, debug, ConfigBuilder, LogLevel};

fn main() {
    // Configure LumeLog
    let config = ConfigBuilder::new().build().unwrap();

    // Example log messages
    info!("This is an informational message");
    warn!("This is a warning!");
    error!("This is an error!");

    //Example with variables
    let test_var = "some data to test"
    debug!("This is debug variable value: {}", test_var)
}

Configuration

You can customize LumeLog using the ConfigBuilder. Here’s what you can configure:

Log Levels

  • ERROR
  • WARN
  • INFO
  • DEBUG
  • TRACE

Example:

let config = ConfigBuilder::new()
    .log_level(Some(LogLevel::DEBUG)) // Log all messages down to DEBUG
    .build()
    .unwrap();

File Logging

Enable file logging with automatic directory creation and specify format:

use lumelog::{FileLoggerBuilder, FileLoggerFormat};

let mut file_logger = FileLoggerBuilder::new();
file_logger.enabled = true;  // Enable file logging
file_logger = file_logger
    .dir_path(Some("logs".to_string()))      // Specify directory (creates if needed)
    .log_format(FileLoggerFormat::JSON);     // Set file format to JSON

let config = ConfigBuilder::new()
    .file_logger_config(Some(file_logger))
    .build()
    .unwrap();

Advanced File Logging Examples

// Nested directory creation (automatically created)
let file_logger = FileLoggerBuilder::new()
    .dir_path(Some("app/logs/2024".to_string()))
    .log_format(FileLoggerFormat::TEXT);

// Default directory (uses "logs" if not specified)
let file_logger = FileLoggerBuilder::new()
    .dir_path(None)  // Defaults to "logs" directory
    .log_format(FileLoggerFormat::JSON);

Logging Macros

LumeLog provides easy-to-use macros for logging messages at various levels:

  • info!: Logs informational messages.
  • warn!: Logs warnings.
  • error!: Logs errors.
  • debug!: Logs debug messages.
  • trace!: Logs trace-level messages.

Example:

info!("User {} has logged in", "Alice");
warn!("Memory usage is high: {}%", 90);
error!("Failed to save data: {}", "Disk full");

Full config struct settings

let mut file_logger = FileLoggerBuilder::new();
file_logger.enabled = true;                          // Enable file logging
file_logger = file_logger
    .dir_path(Some("app_logs".to_string()))          // Directory for log files
    .log_format(FileLoggerFormat::TEXT);             // Format of the log files

ConfigBuilder{
    log_level: Some(lumelog::LogLevel::INFO),        // Log level for the logger.
    log_in_release: true,                            // Enables or disables logging in release mode.
    log_with_time: Some(true),                       // Enables or disables time-stamping in logs.
    std: true,                                       // Enables or disables standard output logging.
    file_logger_config: Some(file_logger),           // Configuration for file-based logging.
}

Build Mode Detection

LumeLog automatically detects build mode (debug or release) and adjusts logging behavior accordingly. You can override this behavior using the log_in_release configuration.

!NOTE: If log_in_release is enabled, trace and debug messages will not be logged.

πŸ—οΈ Architecture

LumeLog is designed with performance and flexibility in mind:

Core Components

  • LogLevel: Enum defining log severity levels with proper ordering
  • Config: Global configuration managed by OnceCell for thread-safe single initialization
  • FileLogger: Configurable file output with multiple format support
  • Macros: Zero-cost abstractions for logging with compile-time optimization

Thread Safety

  • OnceCell: Ensures global configuration is set exactly once
  • Atomic Operations: Thread-safe access to configuration
  • No Locks: Runtime logging operations are lock-free for performance

Performance Characteristics

  • Zero Runtime Cost: Logging calls are no-ops when disabled at compile time
  • Minimal Allocations: Efficient string formatting and I/O operations
  • Conditional Compilation: Debug vs release mode optimizations

File Format Support

// Text format (default) - logs/app_20241019.log
2023-10-18 14:30:25 INFO User login successful

// JSON format - logs/app_20241019.json
{"timestamp":"2023-10-18T14:30:25Z","level":"INFO","message":"User login successful"}

Directory Management Features

  • Automatic Creation: Nested directories are created automatically (logs/app/2024/october)
  • Fallback Handling: Empty or None paths default to "logs" directory
  • Date-Based Files: Log files include timestamps for organization
  • Cross-Platform: Works on Windows, macOS, and Linux file systems
  • Permission Handling: Graceful handling of permission errors

🎨 Console Output Examples

LumeLog provides beautifully styled console output:

 ERROR  Critical system failure detected
 WARN   High memory usage: 89%
 INFO   Application started successfully  
 DEBUG  Processing user request: /api/users
 TRACE  Database query executed in 12ms

Each level has its own distinct color scheme for quick visual identification.

πŸ”§ Troubleshooting

Common Issues

Q: Tests fail with "OnceCell already initialized" error

# Solution: Run tests sequentially
make test
# OR
cargo test --test main -- --test-threads=1

Q: Logs not appearing in release mode

// Solution: Enable release logging
ConfigBuilder::new()
    .log_in_release(true)  // Enable this flag
    .build()
    .unwrap();

Q: File logging not working

// Solution: Ensure file logger is enabled and directory is specified
let mut file_logger = FileLoggerBuilder::new();
file_logger.enabled = true;  // Don't forget this!
file_logger = file_logger.dir_path(Some("logs".to_string()));

Q: Configuration can't be changed after first setup

This is expected behavior! LumeLog uses OnceCell for thread-safe 
single initialization. The configuration is global and immutable 
after the first call to .build().

πŸ§ͺ Testing

LumeLog comes with a comprehensive test suite that ensures reliability and correctness across all features.

Test Suite Organization

The project includes 40+ integration tests organized across multiple test files:

tests/main.rs - Core API Tests (21 tests)

  • βœ… OnceCell single initialization behavior
  • βœ… Configuration builder patterns and validation
  • βœ… Log level enumeration and ordering
  • βœ… File logger builder API testing
  • βœ… All logging macro functionality
  • βœ… Thread safety and global state management

tests/file_logging.rs - File Logging Tests (10 tests)

  • βœ… Basic file logging with directory creation
  • βœ… JSON and TEXT format validation
  • βœ… Log level filtering in file output
  • βœ… Formatted message interpolation
  • βœ… Append behavior and message ordering
  • βœ… Timestamp control (with/without timestamps)
  • βœ… Disabled file logging behavior

tests/file_logging_advanced.rs - Advanced Tests (9 tests)

  • βœ… Nested directory creation (logs/nested/deep/directory)
  • βœ… Concurrent logging thread safety (5 threads Γ— 10 messages)
  • βœ… High-volume logging performance (1000+ messages)
  • βœ… Long message handling (5000+ character strings)
  • βœ… Special characters and Unicode support (πŸš€ こんにけは Ξ± Ξ²)
  • βœ… Empty/None path handling with fallback behavior
  • βœ… JSON structure validation
  • βœ… FileLoggerBuilder edge cases and method chaining

Running Tests

Run tests using the Makefile:

make test                 # Run all 40+ tests (sequential for OnceCell safety)
make test-verbose         # Run tests with detailed output
make test-integration     # Run integration tests only
make test-coverage        # Generate coverage report (requires cargo-tarpaulin)

Or use cargo directly:

# Run all tests
cargo test -- --test-threads=1

# Run specific test files
cargo test --test main -- --test-threads=1                    # Core API tests
cargo test --test file_logging -- --test-threads=1            # File logging tests  
cargo test --test file_logging_advanced -- --test-threads=1   # Advanced file tests

Note: Tests are run with --test-threads=1 to ensure proper OnceCell behavior testing, as the global CONFIG can only be initialized once per process.

Test File Organization

tests/
β”œβ”€β”€ main.rs                    # Core API and configuration tests (21 tests)
β”œβ”€β”€ file_logging.rs           # Basic file logging functionality (10 tests) 
β”œβ”€β”€ file_logging_advanced.rs  # Advanced scenarios and edge cases (9 tests)
└── README.md                 # Test documentation and usage guide

Each test file is self-contained with proper setup, execution, and cleanup phases.

πŸ› οΈ Development

This project includes a comprehensive Makefile with useful development commands:

Quick Commands

make help                 # Show all available commands
make build               # Build in debug mode
make build-release       # Build in release mode
make test                # Run tests
make fmt                 # Format code
make clippy              # Run linter
make clean               # Clean build artifacts

Development Workflow

make pre-commit          # Run all pre-commit checks (format, lint, test)
make ci-check           # Run CI pipeline checks
make release-check      # Full release validation

Documentation

make doc                # Generate documentation
make doc-open           # Generate and open docs in browser

Maintenance

make deps               # Install development dependencies
make update             # Update dependencies  
make audit              # Security audit
make info               # Show project information

πŸ“ˆ Recent Updates (v0.1.7)

πŸ†• What's New

  • Enhanced File Logging API: Updated to use dir_path for automatic directory creation
  • Comprehensive Test Suite: Expanded to 40+ integration tests organized across 3 test files
  • Advanced File Logging Tests: Added support for nested directories, Unicode, and high-volume logging
  • Improved Thread Safety: Extensive concurrent logging tests with 5 threads Γ— 10 messages each
  • Performance Testing: High-volume logging validation with 1000+ messages
  • Edge Case Coverage: Comprehensive testing of special characters, long messages, and error conditions

πŸ”§ Testing Infrastructure Improvements

  • Organized Test Files: Separated tests into logical files (main.rs, file_logging.rs, file_logging_advanced.rs)
  • Advanced Scenarios: Added tests for nested directory creation, concurrent access, and Unicode support
  • Performance Validation: Tests verify logging performance under high load
  • Real-World Scenarios: Tests simulate actual usage patterns with formatted messages and file operations
  • Automatic Cleanup: All tests properly clean up temporary directories and files

πŸ› οΈ API Enhancements

  • Directory-Based Logging: Changed from single file to directory-based logging with dir_path
  • Automatic Directory Creation: Supports nested paths like logs/app/2024/october
  • Fallback Behavior: Defaults to "logs" directory when path is empty or None
  • Enhanced Builder Pattern: More intuitive FileLoggerBuilder configuration
  • Better Error Handling: Improved error messages and graceful degradation

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Run tests and checks: make pre-commit
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

πŸ“Š Project Stats

Metric Value
Lines of Code ~800+
Test Coverage 40+ integration tests across 3 files
Makefile Commands 30+ development commands
Dependencies 3 (minimal footprint)
Rust Edition 2021
MSRV 1.56+
Test Categories Core API (21) + File Logging (19)

πŸ”— Links

πŸ™ Acknowledgments

  • Built with ❀️ by Kyrylenko Yevhen
  • Inspired by the need for simple, effective logging in Rust
  • Thanks to the Rust community for excellent crates: chrono, colored, once_cell

If LumeLog helps your project, consider giving it a ⭐ on GitHub!

Made with πŸ¦€ and β˜• by LinearDev

οΏ½πŸ“„ License

LumeLog is dual-licensed under the MIT or Apache 2.0 license. See LICENSE-MIT or LICENSE-APACHE for details.

Commit count: 10

cargo fmt