
Table of Contents
TL;DR
Installing the library
Quick start
# use ;
debug!;
info!;
warn!;
err!;
fatal!;
The Logger
The Logger struct only handles log filtering, relying on LogFormatter and
LogOutput for formatting and outputting the logs.
Creating a Logger struct with default configuration:
# use Logger;
let mut logger = default;
Log filtering
Logs are filtered based on their importance and the verbosity setting.
Setting logger verbosity:
# use ;
# let mut logger = default;
logger.set_verbosity;
Toggling log filtering:
# use ;
# let mut logger = default;
logger.enable_log_filtering;
logger.disable_log_filtering;
Logger templates
A Logger template is serialized Logger struct in JSON format. Logger
templates can be used to easily manage and store logger configurations in files.
Here’s an example of what a serialized Logger struct looks like in JSON:
Loading Logger from a template file:
# use Logger;
# let mut path = temp_dir;
# path.push;
# let path = path.to_str.unwrap.to_string;
# default.save_template;
let mut logger = from_template;
Deserializing Logger from a JSON string:
# use Logger;
// Obtain a deserializable string
let raw_json = to_string
.expect;
// Deserialize `Logger` from a string
let logger = from_template_str
.expect;
# assert_eq!;
Saving Logger to a template file:
# use Logger;
# let mut path = temp_dir;
# path.push;
# let path = &path.to_str.unwrap.to_string;
let mut logger = default;
logger.save_template;
Global logger instance
The prettylogger crate defines a global logger instance wrapped in RwLock,
which you can share between multiple threads.
Modifying the global logger configuration:
# use ;
// Get write access to the logger
let mut logger = LOGGER.write.unwrap;
// Modify the logger
logger.set_verbosity;
Using the global logger:
# use LOGGER;
// Get read access to the logger
let logger = LOGGER.read.unwrap;
// Print some logs
logger.info;
Requiring read access to the global logger in every function you use is tedious,
isn't it? Furthermore, because its methods only accept &str as message
arguments, you’d have to handle all message formatting yourself.
Fortunately, there is a set of macros designed just to solve this issue.
Using logging macros to print some messages with the global logger:
# use ;
debug!;
info!;
warn!;
err!;
fatal!;
Logging macros accept arguments just like the format! macro:
# use info;
let some_value = 32;
let name = "User";
info!;
[!WARNING] Since the logging macros acquire read access to the global logger under the hood, they will block your thread if there is another process with write access to the logger.
This will block the thread:
# use prettylogger::{info, glob::LOGGER}; // Get write access to the logger let mut logger = LOGGER.write().unwrap(); // Trying to use logging macro blocks the thread info!("This will never be shown!");
Log formatting
LogFormatter
The LogFormatter struct manages log formatting. It's accessible as a field
within Logger, but can also operate independently.
Using a LogFormatter:
# use ;
// Create a `LogFormatter` with default configuration
let mut formatter = default;
// Set a log format
formatter.set_log_format;
// Obtain a formatted log from a `LogStruct`
let log = formatter.format_log;
// Print the formatted log message
print!;
Log format
A log consists of several headers:
- Log Type → The type of the log (debug, info, warning etc.)
- Timestamp → Contains the date and time the log was created
- Message → The actual log message
These headers can then be formatted using a log format string, similarly to how you would format datetime with a datetime format string.
Here is a log message with all its headers marked:
[ DEBUG 21:52:37 An example debug message ]
^^^^^ ^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
| | |
| | the message
| timestamp
log type
This specific effect was achieved by setting the datetime format to %H:%M:%S,
log format to [ %h %d %m ] and the debug log type header to DEBUG.
Setting datetime format of a LogFormatter:
# use LogFormatter;
let mut formatter = default;
formatter.set_datetime_format;
Setting a custom log format:
# use LogFormatter;
let mut formatter = default;
formatter.set_log_format;
[!NOTE] The
%m(message) placeholder is mandatory. You will get an error unless you include it in your format string.
Customizing log headers:
# use LogFormatter;
let mut formatter = default;
formatter.set_debug_header;
formatter.set_info_header;
formatter.set_warning_header;
formatter.set_error_header;
formatter.set_fatal_header;
Setting custom log header colors:
# use ;
let mut formatter = default;
formatter.set_debug_color;
formatter.set_info_color;
formatter.set_warning_color;
formatter.set_error_color;
formatter.set_fatal_color;
Using the LogStruct
LogStruct is a type that represents a single log entry. This is the raw,
non-formatted log message used internally by Logger, LogFormatter and
log streams.
Creating a LogStruct and formatting it with a LogFormatter:
# use ;
let mut formatter = default;
// Create a `LogStruct`
let raw_log = debug;
// Format the `LogStruct`
let formatted_log = formatter.format_log;
// Print the formatted log
print!;
Log outputs
Log outputs determine how messages are routed, delivering logs to specific
destinations like standard error (StderrStream) or a dedicated log file
(FileStream). Each output can be selectively toggled. Additionally, the
parent output provides an overall control mechanism; disabling it effectively
halts all child streams.
LogOutput (parent)
LogOutput is used internally by the Logger struct for handling it's child
output streams. Toggling it affects all of its child streams.
StderrStream
This is the simplest of the log outputs. It formats the given log using the
formatter and prints it to stderr.
Printing a log to stderr:
# use ;
// Required by `StderrStream` for parsing logs
let mut formatter = default;
// Enabled by default
let mut stderr_output = default;
// Print "Hello, World!" in a neat format
stderr_output.out;
BufferStream
When enabled, BufferStream stores raw logs in an internal buffer. This means
that it doesn't need a formatter.
Using BufferStream:
# use ;
let mut buffer_stream = default;
// Enable the buffer stream
buffer_stream.enable;
// Write to the buffer 128 times
for i in 0..128
// Get a reference to the log buffer
let buffer = buffer_stream.get_log_buffer;
# assert_eq!;
// Do whatever you wish with the log buffer here
// Clear the log buffer
buffer_stream.clear;
FileStream
FileStream is used for storing logs in a log file. FileStream utilizes an
internal log buffer for storing already formatted log messages until they are
written to the log file.
Using FileStream:
# use ;
# let mut path = temp_dir;
# path.push;
# let path = &path.to_str.unwrap.to_string;
let mut formatter = default;
let mut file_stream = default;
// Set the log file path before enabling the stream
file_stream.set_log_file_path
.expect;
// Enable the stream after the log file path has been set
file_stream.enable
.expect;
// Write to the log buffer
file_stream.out
.expect;
// Write the contents of the log buffer to the log file
file_stream.flush
.expect;
[!NOTE] The log file path has to be set in order to enable and use the file stream.
Automatic log buffer flushing
FileStream can automatically write to the log file when its log buffer
exceeds a specific limit. Setting this limit to None will disable this
feature.
Example:
# use ;
# let mut path = temp_dir;
# path.push;
# let path = &path.to_str.unwrap.to_string;
let mut formatter = default;
// Configure the `FileStream`
let mut file_stream = default;
file_stream.set_log_file_path
.expect;
file_stream.enable
.expect;
// Set the log file buffer limit to 128
file_stream.set_max_buffer_size;
// Write to the log buffer 128 times
for i in 0..128
// Here the log buffer will automatically be flushed.
Locking the log file
The log file can be locked to prevent race conditions when there are multiple
threads accessing it at the same time. It stops FileStream from writing to
it until the lock has been released. The lock is only ignored when
FileStream is being dropped and the OnDropPolicy is set to
IgnoreLogFileLock (off by default).
Toggling the lock:
# use FileStream;
# let mut file_stream = default;
// Lock the log file
file_stream.lock_file;
// Unlock the log file
file_stream.unlock_file;
Setting on drop policy:
# use ;
# let mut file_stream = default;
file_stream.set_on_drop_policy;