Crate log [] [src]

🔬 This is a nightly-only experimental API. (rustc_private)

this crate is being loaded from the sysroot, and unstable location; did you mean to load this crate from crates.io via Cargo.toml instead?

A lightweight logging facade.

The log crate provides a single logging API that abstracts over the actual logging implementation. Libraries can use the logging API provided by this crate, and the consumer of those libraries can choose the logging framework that is most suitable for its use case.

If no logging implementation is selected, the facade falls back to a "noop" implementation that ignores all log messages. The overhead in this case is very small - just an integer load, comparison and jump.

A log request consists of a target, a level, and a body. A target is a string which defaults to the module path of the location of the log request, though that default may be overridden. Logger implementations typically use the target to filter requests based on some user configuration.

Use

In libraries

Libraries should link only to the log crate, and use the provided macros to log whatever information will be useful to downstream consumers.

Examples

#[macro_use]
extern crate log;

pub fn shave_the_yak(yak: &Yak) {
    info!(target: "yak_events", "Commencing yak shaving for {:?}", yak);

    loop {
        match find_a_razor() {
            Ok(razor) => {
                info!("Razor located: {}", razor);
                yak.shave(razor);
                break;
            }
            Err(err) => {
                warn!("Unable to locate a razor: {}, retrying", err);
            }
        }
    }
}

In executables

Executables should choose a logging framework and initialize it early in the runtime of the program. Logging frameworks will typically include a function to do this. Any log messages generated before the framework is initialized will be ignored.

The executable itself may use the log crate to log as well.

Warning

The logging system may only be initialized once.

Examples

#[macro_use]
extern crate log;
extern crate env_logger;

fn main() {
    // Select env_logger, one possible logger implementation
    // (see https://doc.rust-lang.org/log/env_logger/index.html)
    env_logger::init().unwrap();
     
    info!("starting up");
    error!("error: {}", 404);
     
    // ...
}

Logger implementations

Loggers implement the Log trait. Here's a very basic example that simply logs all messages at the Error, Warn or Info levels to stdout:

extern crate log;

use log::{LogRecord, LogLevel, LogMetadata};

struct SimpleLogger;

impl log::Log for SimpleLogger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= LogLevel::Info
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            println!("{} - {}", record.level(), record.args());
        }
    }
}

Loggers are installed by calling the set_logger function. It takes a closure which is provided a MaxLogLevelFilter token and returns a Log trait object. The MaxLogLevelFilter token controls the global maximum log level. The logging facade uses this as an optimization to improve performance of log messages at levels that are disabled. In the case of our example logger, we'll want to set the maximum log level to Info, since we ignore any Debug or Trace level log messages. A logging framework should provide a function that wraps a call to set_logger, handling initialization of the logger:

pub fn init() -> Result<(), SetLoggerError> {
    log::set_logger(|max_log_level| {
        max_log_level.set(LogLevelFilter::Info);
        Box::new(SimpleLogger)
    })
}

Use with no_std

To use the log crate without depending on libstd, you need to specify default-features = false when specifying the dependency in Cargo.toml. This makes no difference to libraries using log since the logging API remains the same. However executables will need to use the set_logger_raw function to initialize a logger and the shutdown_logger_raw function to shut down the global logger before exiting:

pub fn init() -> Result<(), SetLoggerError> {
    unsafe {
        log::set_logger_raw(|max_log_level| {
            static LOGGER: SimpleLogger = SimpleLogger;
            max_log_level.set(LogLevelFilter::Info);
            &SimpleLogger
        })
    }
}
pub fn shutdown() -> Result<(), ShutdownLoggerError> {
    log::shutdown_logger_raw().map(|logger| {
        let logger = unsafe { &*(logger as *const SimpleLogger) };
        logger.flush();
    })
}

Macros

debug [
Experimental
]

Logs a message at the debug level.

error [
Experimental
]

Logs a message at the error level.

info [
Experimental
]

Logs a message at the info level.

log [
Experimental
]

The standard logging macro.

log_enabled [
Experimental
]

Determines if a message logged at the specified level in that module will be logged.

trace [
Experimental
]

Logs a message at the trace level.

warn [
Experimental
]

Logs a message at the warn level.

Structs

LogLocation [
Experimental
]

The location of a log message.

LogMetadata [
Experimental
]

Metadata about a log message.

LogRecord [
Experimental
]

The "payload" of a log message. This structure is primarily used as a parameter in the log method of the Log trait.

MaxLogLevelFilter [
Experimental
]

A token providing read and write access to the global maximum log level filter.

SetLoggerError [
Experimental
]

The type returned by set_logger if set_logger has already been called.

ShutdownLoggerError [
Experimental
]

The type returned by shutdown_logger_raw if shutdown_logger_raw has already been called or if set_logger_raw has not been called yet.

Enums

LogLevel [
Experimental
]

An enum representing the available verbosity levels of the logging framework.

LogLevelFilter [
Experimental
]

An enum representing the available verbosity level filters of the logging framework.

Traits

Log [
Experimental
]

A trait encapsulating the operations required of a logger

Functions

max_log_level [
Experimental
]

Returns the current maximum log level.

set_logger [
Experimental
]

Sets the global logger.

set_logger_raw [
Experimental
]

Sets the global logger from a raw pointer.

shutdown_logger [
Experimental
]

Shuts down the global logger.

shutdown_logger_raw [
Experimental
]

Shuts down the global logger.