Master Rust Logging with log4rs: A Step-by-Step Guide

This article introduces Rust's log4rs library, explains its core concepts of appenders and loggers, and provides complete code examples for configuring system and business log files, initializing the logger, and handling command‑line log commands in a Rust application.

JD Cloud Developers
JD Cloud Developers
JD Cloud Developers
Master Rust Logging with log4rs: A Step-by-Step Guide

log4rs Basic Concepts

log4rs's functionality consists of appenders and loggers .

Appender : responsible for appending logs to a specified file or console.

Logger : contains multiple appenders; for example, a log can be output to both the console and a file by binding ConsoleAppender and FileAppender in a logger.

log4rs Usage Example

Example Description

We need to record system logs and business logs in logs/sys.log and logs/business.log respectively.

Define appender and logger and initialize

Code location:

src/logger/logger.rs
let sys_file = FileAppender::builder()
    .encoder(Box::new(PatternEncoder::new("{d} - {m}{n}")))
    .build("logs/sys.log")
    .unwrap();
let business_file = FileAppender::builder()
    .encoder(Box::new(PatternEncoder::new("{d} - {m}{n}")))
    .build("logs/business.log")
    .unwrap();

let stdout = ConsoleAppender::builder().build();

let config = Config::builder()
    .appender(Appender::builder().build("stdout", Box::new(stdout)))
    .appender(Appender::builder().build("sys", Box::new(sys_file)))
    .appender(Appender::builder().build("business", Box::new(business_file)))
    .logger(
        Logger::builder()
            .appender("sys")
            .build("syslog", LevelFilter::Info),
    )
    .logger(
        Logger::builder()
            .appender("business")
            .build("businesslog", LevelFilter::Info),
    )
    .build(
        Root::builder()
            .appender("stdout")
            .appender("file_out")
            .build(LevelFilter::Info),
    )
    .unwrap();

let _ = log4rs::init_config(config).unwrap();

Output logs in program

Define the uselog command with two sub‑commands to input system and business logs.

Code location:

src/cmd/cmdusedifflogger.rs
pub fn new_use_sys_log_cmd() -> Command<'static> {
    clap::Command::new("syslog").about("append to syslog")
}

pub fn new_use_business_log_cmd() -> Command<'static> {
    clap::Command::new("businesslog").about("append to business log")
}

Parse command and output logs

Code location:

src/cmd/rootcmd.rs
if let Some(ref log) = matches.subcommand_matches("uselog") {
    println!("use log");
    if let Some(_) = log.subcommand_matches("syslog") {
        log::info!(target:"syslog","Input sys log");
    }
    if let Some(_) = log.subcommand_matches("businesslog") {
        log::info!(target:"businesslog","Input business log");
    }
}

When outputting, the target distinguishes which logger receives the message.

GitHub repository: https://github.com/jiashiwen/interactcli-rs

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CLIlogginglog4rs
JD Cloud Developers
Written by

JD Cloud Developers

JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.