Crate log4rs

source ·
Expand description

log4rs is a highly configurable logging framework modeled after Java’s Logback and log4j libraries.

§Architecture

The basic units of configuration are appenders, encoders, filters, and loggers.

§Appenders

An appender takes a log record and logs it somewhere, for example, to a file, the console, or the syslog.

Implementations:

  • console: requires the console_appender feature.
  • file: requires the file_appender feature.
  • rolling_file: requires the rolling_file_appender feature and can be configured with the compound_policy.
    • compound: requires the compound_policy feature
      • Rollers
        • delete: requires the delete_roller feature
        • fixed_window: requires the fixed_window_roller feature
      • Triggers
        • size: requires the size_trigger feature
        • time: requires the time_trigger feature

§Encoders

An encoder is responsible for taking a log record, transforming it into the appropriate output format, and writing it out. An appender will normally use an encoder internally.

Implementations:

  • pattern: requires the pattern_encoder feature
  • json: requires the json_encoder feature

§Filters

Filters are associated with appenders and, like the name would suggest, filter log events coming into that appender.

Implementations:

  • threshold: requires the threshold_filter feature

§Loggers

A log event is targeted at a specific logger, which are identified by string names. The logging macros built in to the log crate set the logger of a log event to the one identified by the module containing the invocation location.

Loggers form a hierarchy: logger names are divided into components by “::”. One logger is the ancestor of another if the first logger’s component list is a prefix of the second logger’s component list.

Loggers are associated with a maximum log level. Log events for that logger with a level above the maximum will be ignored. The maximum log level for any logger can be configured manually; if it is not, the level will be inherited from the logger’s parent.

Loggers are also associated with a set of appenders. Appenders can be associated directly with a logger. In addition, the appenders of the logger’s parent will be associated with the logger unless the logger has its additive set to false. Log events sent to the logger that are not filtered out by the logger’s maximum log level will be sent to all associated appenders.

The “root” logger is the ancestor of all other loggers. Since it has no ancestors, its additivity cannot be configured.

§Configuration

For a detailed breakdown on configuration, refer to the config module.

log4rs makes heavy use of Cargo features to enable consumers to pick the functionality they wish to use. File-based configuration requires the file feature, and each file format requires its own feature as well. In addition, each component has its own feature. For example, YAML support requires the yaml_format feature and the console appender requires the console_appender feature.

By default, the all_components, gzip, file, and yaml_format features are enabled.

As a convenience, the all_components feature activates all logger components.

§Examples

§Configuration via a YAML file

# Scan this file for changes every 30 seconds
refresh_rate: 30 seconds

appenders:
  # An appender named "stdout" that writes to stdout
  stdout:
    kind: console

  # An appender named "requests" that writes to a file with a custom pattern encoder
  requests:
    kind: file
    path: "log/requests.log"
    encoder:
      pattern: "{d} - {m}{n}"

# Set the default logging level to "warn" and attach the "stdout" appender to the root
root:
  level: warn
  appenders:
    - stdout

loggers:
  # Raise the maximum log level for events sent to the "app::backend::db" logger to "info"
  app::backend::db:
    level: info

  # Route log events sent to the "app::requests" logger to the "requests" appender,
  # and *not* the normal appenders installed at the root
  app::requests:
    level: info
    appenders:
      - requests
    additive: false

Add the following in your application initialization.

log4rs::init_file("log4rs.yml", Default::default()).unwrap();

§Programmatically constructing a configuration:

use log::LevelFilter;
use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender;
use log4rs::encode::pattern::PatternEncoder;
use log4rs::config::{Appender, Config, Logger, Root};

fn main() {
    let stdout = ConsoleAppender::builder().build();

    let requests = FileAppender::builder()
        .encoder(Box::new(PatternEncoder::new("{d} - {m}{n}")))
        .build("log/requests.log")
        .unwrap();

    let config = Config::builder()
        .appender(Appender::builder().build("stdout", Box::new(stdout)))
        .appender(Appender::builder().build("requests", Box::new(requests)))
        .logger(Logger::builder().build("app::backend::db", LevelFilter::Info))
        .logger(Logger::builder()
            .appender("requests")
            .additive(false)
            .build("app::requests", LevelFilter::Info))
        .build(Root::builder().appender("stdout").build(LevelFilter::Warn))
        .unwrap();

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

    // use handle to change logger configuration at runtime
}

For more examples see the examples.

Re-exports§

Modules§

Structs§

  • A handle to the active logger.
  • The fully configured log4rs Logger which is appropriate to use with the log::set_boxed_logger function.