Logging with log4rs


Dependencies


examples/logging/try-log4rs/Cargo.toml
[package]
name = "try-log4rs"
version = "0.1.0"
edition = "2021"

[dependencies]
log = "0.4.22"
log4rs = "1.3.0"

The code:


examples/logging/try-log4rs/src/main.rs
fn main() {
    log4rs::init_file("log4rs.yaml", Default::default()).unwrap();

    log::trace!("This is a sample trace.");
    log::debug!("This is a sample debug.");
    log::info!("This is a sample info.");
    log::warn!("This is a sample warn.");
    log::error!("This is a sample error.");

    tools::do_something();
}

mod tools {
    pub fn do_something() {
        log::trace!("do_something trace.");
        log::debug!("do_something debug.");
        log::info!("do_something info.");
        log::warn!("do_something warn.");
        log::error!("do_something error.");
    }
}

The configuration


examples/logging/try-log4rs/log4rs.yaml
appenders:
  stdout:
    kind: console
  all:
    kind: file
    path: "all.log"
    encoder:
      pattern: "{d} - {l} {f}:{L} {m}{n}"

root:
  level: debug
  appenders:
    - stdout

loggers:
   try_log4rs::tools:
     level: trace
     appenders:
       - all

Standard output:


2024-08-11T12:13:17.484418418+03:00 DEBUG try_log4rs - This is a sample debug.
2024-08-11T12:13:17.484549182+03:00 INFO try_log4rs - This is a sample info.
2024-08-11T12:13:17.484559672+03:00 WARN try_log4rs - This is a sample warn.
2024-08-11T12:13:17.484566695+03:00 ERROR try_log4rs - This is a sample error.
2024-08-11T12:13:17.484595188+03:00 TRACE try_log4rs::tools - do_something trace.
2024-08-11T12:13:17.484609084+03:00 DEBUG try_log4rs::tools - do_something debug.
2024-08-11T12:13:17.484620947+03:00 INFO try_log4rs::tools - do_something info.
2024-08-11T12:13:17.484632638+03:00 WARN try_log4rs::tools - do_something warn.
2024-08-11T12:13:17.484644481+03:00 ERROR try_log4rs::tools - do_something error.

The all.log file:


examples/logging/try-log4rs/all.log
2024-08-11T12:13:17.484581753+03:00 - TRACE src/main.rs:16 do_something trace.
2024-08-11T12:13:17.484603574+03:00 - DEBUG src/main.rs:17 do_something debug.
2024-08-11T12:13:17.484615887+03:00 - INFO src/main.rs:18 do_something info.
2024-08-11T12:13:17.484627539+03:00 - WARN src/main.rs:19 do_something warn.
2024-08-11T12:13:17.484639321+03:00 - ERROR src/main.rs:20 do_something error.