Skip to content
프로젝트

소개

A versatile and extensible logging implementation.

개발 도구

이 수치를 측정하는 방법

측정된 스타 증가

in 24h
+4
in 7 days
+7
in 15 days
+9
in 1 month
기록 수집 중

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

Logforth

Crates.io Documentation MSRV 1.91 Apache 2.0 licensed Build Status

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.

Getting started

Native structured logging

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-text

The 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:5 server listening port=8080 tls=false

Composing pipelines

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-text
use 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,"column":5,"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,"column":5,"message":"payment gateway slow","attributes":{"order_id":42,"retry":1}}

Working with the log crate

Enable starter-log to collect logs emitted through the log crate with RUST_LOG filtering:

cargo add log
cargo add logforth --features starter-log
fn 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();
}

Examples

Runnable end-to-end scenarios live in the examples workspace crate.

Built-in components and feature flags

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, ValueSerde 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 Stdout and File format records through a Layout, whereas structured appenders such as Journald and OpentelemetryLog encode record fields directly.
  • Keys prefixed with logforth. are reserved by Logforth, and well-known keys such as trace_id and span_id propagate trace context across diagnostics, layouts, and appenders; see DESIGN.md for the full naming conventions.

Extending Logforth

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.

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

관련 프로젝트 살펴보기

불러오는 중…