Logforth is a structured logging framework for Rust built around composable logger pipelines.
A logger pipeline consists of one or more dispatches, each of which filters, enriches, and routes log records to one or more appenders. The same call site can send terse alerts to the terminal, detailed JSON lines to rotated files, and structured events to telemetry backends like OpenTelemetry without duplicating logging code.
Loggers are ordinary values rather than a mandatory global singleton. Applications and libraries can pass separate Logger instances to subsystems or tests, or install one globally to collect log records from the wider Rust ecosystem.
Logforth is self-contained for structured logging with no mandatory external dependencies.
Add it to your Cargo.toml with layout-text for human-readable timestamps and colored levels:
cargo add logforth --features layout-textThe native logging macros take a Logger directly:
use logforth::append::Stderr;
use logforth::layout::TextLayout;
fn main() {
let logger = logforth::builder()
.dispatch(|d| d.append(Stderr::new().with_layout(TextLayout::new())))
.build();
logforth::info!(logger, ["port" = 8080, "tls" = false], "server listening");
logger.flush();
}The line written to standard error will look like this:
2024-08-11T22:44:57.172105+08:00 INFO server: main.rs:9 server listening port=8080 tls=false
Combine independent dispatches to write all events to daily-rotated JSON files while printing only warnings and errors to standard error:
cargo add logforth --features append-file,layout-json,layout-textuse logforth::append::Stderr;
use logforth::append::file::FileBuilder;
use logforth::layout::JsonLayout;
use logforth::layout::TextLayout;
use logforth::record::Level;
use logforth::record::LevelFilter;
fn main() -> Result<(), logforth::Error> {
let json_file = FileBuilder::new("logs", "checkout")
.filename_suffix("jsonl")
.layout(JsonLayout::new())
.rollover_daily()
.build()?;
let stderr = Stderr::new().with_layout(TextLayout::new());
let logger = logforth::builder()
.dispatch(|d| d.append(json_file))
.dispatch(|d| {
d.filter(LevelFilter::MoreSevereEqual(Level::Warn))
.append(stderr)
})
.build();
logforth::info!(logger, ["order_id" = 42], "order accepted");
logforth::warn!(logger, ["order_id" = 42, "retry" = 1], "payment gateway slow");
logger.flush();
Ok(())
}Only payment gateway slow appears on standard error, while logs/checkout.<date>.jsonl records both events:
{"timestamp":"2024-08-11T22:44:57.172246+08:00","level":"INFO","module_path":"checkout","file":"src/main.rs","line":25,"message":"order accepted","attributes":{"order_id":42}}
{"timestamp":"2024-08-11T22:44:57.172310+08:00","level":"WARN","module_path":"checkout","file":"src/main.rs","line":26,"message":"payment gateway slow","attributes":{"order_id":42,"retry":1}}Enable starter-log to collect logs emitted through the log crate with RUST_LOG filtering:
cargo add log
cargo add logforth --features starter-logfn main() {
logforth::starter_log::stderr().install();
log::info!(port = 8080; "server started");
log::logger().flush();
}Custom pipelines can also be installed as the global log backend:
use logforth::append::Stderr;
use logforth::starter_log::LogStarterExt;
fn main() {
logforth::builder()
.dispatch(|d| d.append(Stderr::new()))
.install();
log::info!("routed through a custom Logforth pipeline");
log::logger().flush();
}Runnable end-to-end scenarios live in the examples workspace crate.
logforth enables no optional features by default. Enable only the components your application uses:
| Category | APIs | Feature | Use |
|---|---|---|---|
| Core APIs | Logger, Record, kv, info! |
built-in | Build loggers and emit structured records with key-value fields. |
ValueOwned::from_serde |
serde |
Convert serde::Serialize values into kv fields and serialize kv types. |
|
| Appenders | Stdout, Stderr, Testing |
built-in | Write formatted lines to standard output, standard error, or test output. |
File |
append-file |
Write to a single file or time- and size-rotated log files. | |
Async |
append-async |
Offload downstream appender I/O onto a background worker thread. | |
Journald |
append-journald |
Send structured log entries directly to systemd-journald on Unix. |
|
SocketSyslog, PosixSyslog |
append-syslog |
Send logs to local or remote syslog daemons. | |
OpentelemetryLog |
append-opentelemetry |
Export structured OpenTelemetry log batches with trace correlation. | |
FastraceEvent |
append-fastrace |
Attach log records as events on active fastrace spans. |
|
| Layouts | PlainTextLayout |
built-in | Minimal uncolored single-line text output. |
TextLayout |
layout-text |
Human-readable single-line text with timestamps and ANSI colors. | |
LogfmtLayout |
layout-logfmt |
Single-line key=value logfmt output. |
|
JsonLayout |
layout-json |
Single-line JSON output. | |
GoogleCloudLoggingLayout |
layout-google-cloud-logging |
Structured JSON output for Google Cloud Logging. | |
| Filters | LevelFilter |
built-in | Filter records by severity threshold. |
RustLogFilter |
filter-rustlog |
Filter by module or target prefix using RUST_LOG directives. |
|
| Diagnostics | StaticDiagnostic |
built-in | Attach process-wide key-value fields such as service name or version. |
ThreadLocalDiagnostic |
built-in | Attach scoped key-value fields on the current thread. | |
TaskLocalDiagnostic |
diagnostic-task-local |
Attach scoped key-value fields to an async Future. |
|
FastraceDiagnostic |
diagnostic-fastrace |
Attach trace and span IDs from active fastrace spans. |
|
| Bridges | starter_log |
starter-log |
Quick-start presets for installing Logforth as the global log backend. |
LogBridge |
bridge-log, bridge-log-serde |
Forward log records and log::kv fields into a Logger. |
- Stream-based appenders such as
StdoutandFileformat records through aLayout, whereas structured appenders such asJournaldandOpentelemetryLogencode record fields directly. - Keys prefixed with
logforth.are reserved by Logforth, and well-known keys such astrace_idandspan_idpropagate trace context across diagnostics, layouts, and appenders; see DESIGN.md for the full naming conventions.
- Implement
Append,Layout,Filter,Diagnostic, orErrorSinkto add custom destinations, formats, filters, or context sources. - Every component is also published as an individual
logforth-*crate overlogforth-core, alongside standalonelogforth-logfmtandlogforth-sysloglibraries. - Browse the API reference on docs.rs/logforth, architectural guidelines in DESIGN.md, and release notes in CHANGELOG.md.
This crate is built against the latest stable release, and its minimum supported rustc version is 1.91.0.
The policy is that the minimum Rust version required to use this crate can be increased in minor version updates. For example, if Logforth 1.0 requires Rust 1.60.0, then Logforth 1.0.z for all values of z will also require Rust 1.60.0 or newer. However, Logforth 1.y for y > 0 may require a newer minimum version of Rust.
This project is licensed under Apache License, Version 2.0.
The name Logforth comes from an antonym of the Logback project, and may also be read as a homophone of "log force".