Expand description
Fast, highly configurable Rust logging crate.
It is inspired by the C++ logging library spdlog, and we share most of the
same concepts. So if you are already familiar with C++ spdlog
, you should
be able to get started with this crate quite easily. Of course, there are
some differences, you can see Significant differences from C++
spdlog below.
§Table of contents
- Getting started
- Compile-time filters
- Crate feature flags
- Supported Rust versions
- Overview of features
§Getting started
Add this to Cargo.toml
:
[dependencies]
spdlog-rs = "0.4"
spdlog-rs
is highly configurable, and also works out-of-the-box for
lightweight projects. By default, logs will be output to stdout
and
stderr
.
use spdlog::prelude::*;
// Non-severe logs (trace, debug) are ignored by default.
// If you wish to enable all logs, call
spdlog::default_logger().set_level_filter(spdlog::LevelFilter::All);
info!("hello, world!");
error!("oops!");
debug!("3 + 2 = {}", 5);
Output:
[2022-11-02 09:23:12.263] [info] hello, world! [2022-11-02 09:23:12.263] [error] oops! [2022-11-02 09:23:12.263] [debug] 3 + 2 = 5
The basic use is through these logging macros: trace!
, debug!
,
info!
, warn!
, error!
, critical!
, where critical!
represents the most severe logs and trace!
the most verbose. Each of these
macros accept format strings similarly to println!
. All log macros
and common types are already under prelude
module.
§Sink
Many real programs want more than just displaying logs to the terminal.
Sink
s are the objects that actually write logs to their targets. If you
want logs to be written to files as well, FileSink
is what you need.
use spdlog::{prelude::*, sink::FileSink};
let path = "path/to/somewhere.log";
let new_logger = spdlog::default_logger().fork_with(|new| {
let file_sink = Arc::new(FileSink::builder().path(path).build()?);
new.sinks_mut().push(file_sink);
Ok(())
})?;
spdlog::set_default_logger(new_logger);
info!("from now on, logs will be written to both stdout/stderr and the file");
Take a look at sink
module for more interesting sinks, such as
RotatingFileSink
that automatically rotates files by time point or file
size, and AsyncPoolSink
that outputs logs asynchronously.
§Logger
A complex program may consist of many separated components.
Logger
manages, controls and manipulates multiple sinks within it. In
addition to having the global default_logger
, more loggers are allowed
to be configured, stored and used independently.
Logging macros provide an optional parameter logger
. If it is specified,
logs will be processed by the specified logger instead of the global default
logger.
And benefiting from the fact that a logger uses Arc
to store sinks, a sink
can be set and used by more than one logger, and you can combine them as you
like.
use spdlog::prelude::*;
struct AppDatabase {
logger: Logger,
// Database info...
}
impl AppDatabase {
fn new() -> Result<Self> {
let logger = Logger::builder()
.name("database")
// .sink( ... )
// .sink( ... )
// .level_filter( ... )
// ...
.build()?;
Ok(Self { logger, /* Database info... */ })
}
fn query<T>(&self) -> T {
let data = /* Query from the database */
trace!(logger: self.logger, "queried data {}", data);
data
}
}
struct AppNetwork { /* ... */ }
struct AppAuth { /* ... */ }
struct AppBlahBlah { /* ... */ }
§Learn more
Directory ./examples contains more advanced usage examples. You can learn them along with their documentation.
If you have any trouble while using this crate, please don’t hesitate to open a discussion for help. For feature requests or bug reports, please open an issue.
§Compile-time filters
Log levels can be statically disabled at compile time via Cargo features. Log invocations at disabled levels will be skipped and will not even be present in the resulting binary. This level is configured separately for release and debug builds. The features are:
level-off
level-critical
level-error
level-warn
level-info
level-debug
level-trace
release-level-off
release-level-critical
release-level-error
release-level-warn
release-level-info
release-level-debug
release-level-trace
These features control the value of the STATIC_LEVEL_FILTER
constant. The
logging macros check this value before logging a message. By default, no
levels are disabled.
For example, a crate can disable trace level logs in debug builds and trace,
debug, and info level logs in release builds with
features = ["level-debug", "release-level-warn"]
.
§Crate feature flags
The following crate feature flags are available in addition to the filters.
They are configured in your Cargo.toml
.
-
source-location
allows recording the source location of each log. When it is enabled, the source location will be present inRecord
and visible toFormatter
, and formatting patterns related to source location will be available. If you do not want the source location information to appear in your binary file, you may prefer not to enable it. -
flexible-string
improves the performance of formatting records, however it contains unsafe code. For more details, see the documentation ofStringBuf
. -
log
enables the compatibility with log crate. -
native
enables platform-specific components, such assink::WinDebugSink
for Windows,sink::JournaldSink
for Linux, etc. Note If the component requires additional system dependencies, then more granular features need to be enabled as well. -
runtime-pattern
enables the ability to build patterns with runtime template string. SeeRuntimePattern
for more details. -
serde_json
enablesformatter::JsonFormatter
.
§Supported Rust versions
The current minimum supported Rust version is 1.60.
spdlog-rs
is built against the latest Rust stable release, it is not
guaranteed to build on Rust versions earlier than the minimum supported
version.
spdlog-rs
follows the compiler support policy that the latest stable
version and the 3 most recent minor versions before that are always
supported. For example, if the current latest Rust stable version is 1.61,
the minimum supported version will not be increased past 1.58. Increasing
the minimum supported version is not considered a semver breaking change as
long as it complies with this policy.
§Significant differences from C++ spdlog
The significant differences between spdlog-rs
and C++ spdlog
1:
-
spdlog-rs
does not haveregistry
2. You don’t need to register for loggers. -
spdlog-rs
does not havebacktrace
2. -
In
spdlog-rs
,LevelFilter
is a more flexible and readable enum with logical conditions. -
In
spdlog-rs
, there is no “_st” sinks, all sinks are “_mt”. -
daily_file_sink
andhourly_file_sink
in C++spdlog
are merged intoRotatingFileSink
inspdlog-rs
. They correspond to rotation policiesRotationPolicy::Daily
andRotationPolicy::Hourly
. -
async_logger
in C++spdlog
isAsyncPoolSink
inspdlog-rs
. This allows it to be used with synchronous sinks. -
Some sinks in C++
spdlog
are not yet implemented inspdlog-rs
. (Yes, PRs are welcome) -
…
Re-exports§
pub use error::Error;
pub use error::ErrorHandler;
pub use error::Result;
Modules§
- error
- Provides error types.
- formatter
- Provides formatters for sink formatting log records.
- prelude
- Contains all log macros and common types.
- re_
export - Re-exports items from other crates for convenience.
- sink
- Provides sinks to flexibly output log messages to specified targets.
- terminal_
style - Provides stuff related to terminal style.
Macros§
- critical
- Logs a message at the critical level.
- debug
- Logs a message at the debug level.
- error
- Logs a message at the error level.
- info
- Logs a message at the info level.
- log
- Logs a message at the specified level.
- source_
location_ current - Constructs a
SourceLocation
with current source location. - trace
- Logs a message at the trace level.
- warn
- Logs a message at the warn level.
Structs§
- LogCrate
Proxy log
- Proxy layer for compatible log crate.
- Logger
- Manages, controls and manipulates multiple sinks.
- Logger
Builder - Record
- Represents a log record.
- Record
Owned Record
without lifetimes version.- Source
Location - Represents a location in source code.
- Thread
Pool multi-thread
- A thread pool for processing operations asynchronously.
- Thread
Pool Builder multi-thread
Enums§
- Level
- Represents log levels.
- Level
Filter - Represents log level logical filter conditions.
Constants§
- STATIC_
LEVEL_ FILTER - The statically resolved log level filter.
Functions§
- default_
logger - Returns the global default logger.
- init_
env_ level - Initializes environment variable level filters from environment variable
SPDLOG_RS_LEVEL
. - init_
env_ level_ from - Initializes environment variable level filters from a specified environment variable.
- init_
log_ crate_ proxy log
- Initializes the log crate proxy.
- log_
crate_ proxy log
- Returns the global instance of log crate proxy.
- set_
default_ logger - Sets the given logger as the new global default logger.
- swap_
default_ logger - Sets the given logger as the new global default logger, and returns the old one.
Type Aliases§
- String
Buf - A string buffer type.