Skip to content
fastPublic

About

A versatile and extensible logging implementation.

Topics

Resources

Stars

241 stars

Watchers

2 watching

Forks

Repository files navigation

Logforth

Crates.io Documentation MSRV 1.91 Apache 2.0 licensed Build Status

Logforth is a versatile, extensible, and easy-to-use logging framework for Rust applications. It allows you to configure multiple dispatches, filters, and appenders to customize your logging setup according to your needs.

Getting Started

Add logforth to your Cargo.toml with zero optional features required for native logging:

cargo add logforth

If you also want to collect logs emitted through the log crate facade, enable starter-log (or bridge-log):

cargo add log
cargo add logforth -F starter-log

Simple Usage

Build an explicit Logger and emit structured events with Logforth's native logging macros:

use logforth::append;
use logforth::record::Level;
use logforth::record::LevelFilter;

fn main() {
    let logger = logforth::builder()
        .dispatch(|d| {
            d.filter(LevelFilter::MoreSevereEqual(Level::Info))
                .append(append::Stdout::default())
        })
        .build();

    let addr = "127.0.0.1:8080";
    logforth::error!(logger, "This is an error message.");
    logforth::info!(logger, ["port" = 8080, "tls" = true], "listening on {addr}");
    logforth::debug!(logger, "This debug message will not be printed.");
    logger.flush();
}

Interop with the log Crate

With the starter-log feature enabled, you can set up a global log logger driven by the RUST_LOG environment variable, or bridge an existing Logger with LogBridge:

use logforth::bridge::log::LogBridge;
use logforth::starter_log::LogStarterExt;

fn main() {
    // Option 1: Install a global stdout starter (defaults to `error` unless `RUST_LOG` is set, e.g. `RUST_LOG=all`).
    logforth::starter_log::stdout().install();

    // Option 2: Wrap a native `Logger` with `LogBridge` for `log` targets or global installation.
    let logger = logforth::builder()
        .dispatch(|d| d.append(logforth::append::Stdout::default()))
        .build();
    let bridge = LogBridge::new(logger);
    log::info!(logger: bridge, "This info message flows through LogBridge.");
}

Advanced Usage

Configure multiple dispatches with different filters and appenders on a native Logger:

use logforth::append;
use logforth::record::Level;
use logforth::record::LevelFilter;

fn main() {
    let logger = logforth::builder()
        .dispatch(|d| {
            d.filter(LevelFilter::MoreSevereEqual(Level::Error))
                .append(append::Stderr::default())
        })
        .dispatch(|d| {
            d.filter(LevelFilter::MoreSevereEqual(Level::Info))
                .append(append::Stdout::default())
        })
        .build();

    logforth::error!(logger, "This error will be logged to stderr.");
    logforth::info!(logger, ["component" = "server"], "This info will be logged to stdout.");
    logforth::debug!(logger, "This debug message will not be logged.");
    logger.flush();
}

Configure OpenTelemetry appender to export logs to an OpenTelemetry backend (full example):

use logforth::diagnostic::StaticDiagnostic;
use logforth::starter_log::LogStarterExt;

fn main() {
    let static_diagnostic = StaticDiagnostic::new([("node_id", node_id), ("nodegroup", nodegroup)]);

    let runtime = async_runtime();
    let filter = make_rust_log_filter(&opentelemetry.filter);
    let appender = runtime.block_on(async {
        let exporter = opentelemetry_otlp::LogExporter::builder()
            .with_tonic()
            .with_endpoint(&opentelemetry.otlp_endpoint)
            .with_protocol(opentelemetry_otlp::Protocol::Grpc)
            .build()
            .expect("failed to initialize opentelemetry logger");

        append::opentelemetry::OpentelemetryLogBuilder::new(service_name, exporter)
            .label("service.name", service_name)
            .build()
    });

    logforth::builder()
        .dispatch(|b| {
            b.filter(filter)
                .diagnostic(FastraceDiagnostic::default())
                .diagnostic(static_diagnostic)
                .append(appender)
        })
        .install();
}

Features

Dispatches

Logforth supports multiple dispatches, each with its own set of filters and appenders. This allows you to route log messages to different destinations based on their severity or other criteria.

A simple application may only need one dispatch, while a more complex application can have multiple dispatches for different modules or components.

Appenders

Logforth supports a wide range of built-in appenders implemented as separate crates.

  • Stdout and Stderr appenders for console logging.
  • File appender for logging to optionally rolling files.
  • OpentelemetryLog appender for exporting logs to OpenTelemetry backends.
  • Testing appender that writes log records that can be captured by a test harness.
  • FastraceEvent appender that writes log records to the Fastrace tracing system.
  • Async combiner appender that makes another appender asynchronous.
  • Syslog and Journald appenders for logging to system log services.

Users can also create their own appenders by implementing the Append trait.

Layouts

Some appenders support customizable layouts for formatting log records. Logforth provides several built-in layouts:

Users can also create their own layouts by implementing the Layout trait.

The following appenders do not use layouts:

  • Async appender simply forwards log records to another appender; layouts are determined by the inner appender.
  • FastraceEvent appender converts log records into tracing events; layouts are not applicable.
  • OpentelemetryLog appender uses MakeBody trait for converting log records into OpenTelemetry log bodies. The MakeBody trait is more flexible and may optionally use a Layout implementation internally.

Filters

Logforth supports filtering log records at the dispatch level. Log records that do not pass the filters will not be sent to the appenders. Logforth provides several built-in filters:

  • RustLogFilter allows you to configure logging levels by prefix via the famous RUST_LOG directive pattern.

Users can also create their own filters by implementing the Filter trait.

Diagnostics

Logforth supports providing a mapped diagnostic context (MDC) for stamping each log request.

  • StaticDiagnostic allows you to set static key-value pairs for the entire application, like application version or hostname.
  • ThreadLocalDiagnostic provides scoped thread-local key-value pairs via ThreadLocalDiagnostic::scope, returning an RAII guard that restores shadowed entries on drop.
  • TaskLocalDiagnostic allows you to set task-local key-value pairs for async tasks.
  • FastraceDiagnostic integrates with the Fastrace tracing system to provide tracing context (TraceId, SpanId, etc.) as diagnostics.

Users can also provide their own MDC by implementing the Diagnostic trait.

Key-Value Conventions

Keys prefixed with logforth. are reserved by Logforth (for example, "logforth.target" carries explicit target overrides into RustLogFilter), and well-known keys such as "trace_id", "span_id", and "sampled" coordinate context across diagnostics and layouts. Avoid using logforth.* for application-defined fields; see DESIGN.md for the full specification.

Bridges

So far, Logforth provides out-of-the-box integration with the log crate. You can use Logforth as the backend for any crate that uses the log facade.

Documentation

Read the online documents at https://docs.rs/logforth.

Components are organized into several crates:

Minimum Rust version policy

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.

Maturity

This crate has been in development since 2024-08. It is being used in several production systems stable enough to be considered mature, but it is still evolving.

All modular components are factored out into separate crates. We are working to stabilize the core APIs and several core components, and then release them as logforth-core 1.0. Other components will be released as separate crates that depend on logforth-core.

License and Origin

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".

About

A versatile and extensible logging implementation.

Topics

Resources

Stars

241 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages