Snowlog
A structured logging library for Rust that outputs logs in JSON format with support for log rotation, multiple writers, and global logging.
Features
- Structured Logging: Logs are structured as JSON objects with fields like service name, level, message, timestamp, and payload.
- Log Levels: Supports Debug, Info, Warn, Error levels with filtering.
- Writers:
ConsoleWriter: Outputs to stdout.RotationWriter: Writes to files with automatic rotation based on line count.MultiWriter: Combines multiple writers for simultaneous output.
- Global Logger: Uses
OnceLockfor thread-safe global configuration.
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
= "1.0" # For JSON payloads
Usage
Basic Setup
use ;
Using File Rotation
use RotationWriter;
use Path;
let writer = Boxnew;
init;
Multiple Writers
use ;
let multi_writer = Boxnew;
multi_writer.add_writer;
multi_writer.add_writer;
init;
Log Levels
LogLevel::DebugLogLevel::InfoLogLevel::WarnLogLevel::Error
Logs below the set level are filtered out.
API
Logger
Logger::init(level: LogLevel, service: String, writer: Box<dyn Writer + Send>): Initialize the global logger.Logger::debug(message: &str, payload: serde_json::Value)Logger::info(message: &str, payload: serde_json::Value)Logger::warn(message: &str, payload: serde_json::Value)Logger::error(message: &str, payload: serde_json::Value)
Writers
All writers implement the Writer trait.
ConsoleWriter: Prints to stdout.RotationWriter::new(path: &Path, base_filename: String, max_lines: usize): Rotates files whenmax_linesis reached.MultiWriter::new()+add_writer(writer: Box<dyn Writer>): Combines writers.
LogEntry
Represents a log entry. Can be serialized to JSON.
let entry = new;
let json = entry.to_json_string.unwrap;
License
MPL-2.0