log2
log2 is an out-of-the-box logging library for Rust. It writes to stdout or to file asynchronously, and automatically rotates based on file size.
Features
- stdout logging - Log to console with color support
- file logging - Log to file with automatic rotation
- log rotation - Rotate logs based on file size (default: 100MB, 10 files)
- tee support - Log to both file and stdout simultaneously
- module filtering - Filter logs by module path
- custom formatting - Customize log output format
- gzip compression - Compress rotated log files
- globally static - No need to store the logger handle, lives for entire program duration
Add dependency
Quick Start
Log to stdout
use *;
Log to file
use *;
Configuration
stdout with options
use *;
file with options
use *;
API Reference
Functions
| Function | Description |
|---|---|
log2::start() |
Start logging to stdout with default settings |
log2::stdout() -> Log2 |
Create a stdout logger for configuration |
log2::open(path) -> Log2 |
Create a file logger for configuration |
log2::set_level(level) |
Set global log level |
log2::handle() -> Option<RwLockWriteGuard> |
Get the global handle for manipulation |
log2::reset() |
Reset the global logger (useful for testing) |
Log2 Builder Methods
| Method | Description | Default |
|---|---|---|
.level(name) |
Set log level | "trace" |
.module(show) |
Show/hide module path | true |
.module_with_line(show) |
Show module path with line number | false |
.tee(stdout) |
Also output to stdout | false |
.size(bytes) |
Max file size before rotation | 100MB |
.rotate(count) |
Number of rotated files to keep | 10 |
.compress(on) |
Compress rotated files with gzip | false |
.module_filter(fn) |
Filter logs by module path | none |
.format(fn) |
Custom log format function | built-in |
.start() |
Start the logger | - |
Log Levels
trace- Most verbosedebug- Debug informationinfo- General information (default)warn- Warning messageserror- Error messagesoff- Disable all logging
Log Macros
use *;
trace!;
debug!;
info!;
warn!;
error!;
Handle API
You can manipulate the logger after starting:
use *;
Handle Methods
| Method | Description |
|---|---|
stop() |
Stop the logger thread |
flush() |
Flush all pending logs |
redirect(path) |
Redirect log to a new file |
set_level(level) |
Change log level |
Module Filtering
Filter logs by module path:
use *;
Custom Formatter
Create a custom log format:
use Local;
use Record;
use *;
File Rotation
When file size reaches the limit, log2 rotates files:
app.log <- current log
app.1.log <- most recent
app.2.log <- older
...
app.9.log <- oldest
With compression enabled:
app.log
app.1.log.gz
app.2.log.gz
...
app.9.log.gz
Testing
use *;
Dependencies
Add these to your Cargo.toml if you use custom features:
= "0.4" # for timestamp formatting
= "2" # for colored output
= "1" # for gzip compression