Expand description
A simple logger that can be configured via environment variables, for usewith the logging facade exposed by thelog
crate.
Despite having “env” in its name,env_logger
can also be configured byother means besides environment variables. Seethe examplesin the source repository for more approaches.
By default,env_logger
writes logs tostderr
, but can be configured toinstead write them tostdout
.
§Example
uselog::{debug, error, log_enabled, info, Level};env_logger::init();debug!("this is a debug {}","message");error!("this is printed by default");iflog_enabled!(Level::Info) {letx =3*4;// expensive computationinfo!("the answer was: {}", x);}
Assumes the binary ismain
:
$ RUST_LOG=error ./main[2017-11-09T02:12:24Z ERROR main] this is printed by default
$ RUST_LOG=info ./main[2017-11-09T02:12:24Z ERROR main] this is printed by default[2017-11-09T02:12:24Z INFO main] the answer was: 12
$ RUST_LOG=debug ./main[2017-11-09T02:12:24Z DEBUG main] this is a debug message[2017-11-09T02:12:24Z ERROR main] this is printed by default[2017-11-09T02:12:24Z INFO main] the answer was: 12
You can also set the log level on a per module basis:
$ RUST_LOG=main=info ./main[2017-11-09T02:12:24Z ERROR main] this is printed by default[2017-11-09T02:12:24Z INFO main] the answer was: 12
And enable all logging:
$ RUST_LOG=main ./main[2017-11-09T02:12:24Z DEBUG main] this is a debug message[2017-11-09T02:12:24Z ERROR main] this is printed by default[2017-11-09T02:12:24Z INFO main] the answer was: 12
If the binary name contains hyphens, you will need to replacethem with underscores:
$ RUST_LOG=my_app ./my-app[2017-11-09T02:12:24Z DEBUG my_app] this is a debug message[2017-11-09T02:12:24Z ERROR my_app] this is printed by default[2017-11-09T02:12:24Z INFO my_app] the answer was: 12
This is because Rust modules and crates cannot contain hyphensin their name, althoughcargo
continues to accept them.
See the documentation for thelog
crate for moreinformation about its API.
§Enabling logging
By default all logging is disabled except for theerror
level
TheRUST_LOG
environment variable controls logging with the syntax:
RUST_LOG=[target][=][level][,...]
Or in other words, its a comma-separated list of directives.Directives can filter bytarget, bylevel, or both (using=
).
For example,
RUST_LOG=data=debug,hardware=debug
target is typically the path of the module the messagein question originated from, though it can be overridden.The path is rooted in the name of the crate it was compiled for, so ifyour program is in a file called, for example,hello.rs
, the path wouldsimply behello
.
Furthermore, the log can be filtered using prefix-search based on thespecified log target.
For example,RUST_LOG=example
would match the following targets:
example
example::test
example::test::module::submodule
examples::and_more_examples
When providing the crate name or a module path, explicitly specifying thelog level is optional. If omitted, all logging for the item will beenabled.
level is the maximumlog::Level
to be shown and includes:
error
warn
info
debug
trace
off
(pseudo level to disable all logging for the target)
Logging level names are case-insensitive; e.g.,debug
,DEBUG
, anddEbuG
all represent the same logging level. Forconsistency, our convention is to use the lower case names. Where our docsdo use other forms, they do so in the context of specific examples, so youwon’t be surprised if you see similar usage in the wild.
Some examples of valid values ofRUST_LOG
are:
RUST_LOG=hello
turns on all logging for thehello
moduleRUST_LOG=trace
turns on all logging for the application, regardless of its nameRUST_LOG=TRACE
turns on all logging for the application, regardless of its name (same as previous)RUST_LOG=info
turns on all info loggingRUST_LOG=INFO
turns on all info logging (same as previous)RUST_LOG=hello=debug
turns on debug logging forhello
RUST_LOG=hello=DEBUG
turns on debug logging forhello
(same as previous)RUST_LOG=hello,std::option
turns onhello
, and std’s option loggingRUST_LOG=error,hello=warn
turn on global error logging and also warn forhello
RUST_LOG=error,hello=off
turn on global error logging, but turn off logging forhello
RUST_LOG=off
turns off all logging for the applicationRUST_LOG=OFF
turns off all logging for the application (same as previous)
§Filtering results
ARUST_LOG
directive may include a regex filter. The syntax is to append/
followed by a regex. Each message is checked against the regex, and is onlylogged if it matches. Note that the matching is done after formatting thelog string but before adding any logging meta-data. There is a single filterfor all modules.
Some examples:
hello/foo
turns on all logging for the ‘hello’ module where the logmessage includes ‘foo’.info/f.o
turns on all info logging where the log message includes ‘foo’,‘f1o’, ‘fao’, etc.hello=debug/foo*foo
turns on debug logging for ‘hello’ where the logmessage includes ‘foofoo’ or ‘fofoo’ or ‘fooooooofoo’, etc.error,hello=warn/[0-9]scopes
turn on global error logging and alsowarn for hello. In both cases the log message must include a single digitnumber followed by ‘scopes’.
§Capturing logs in tests
Records logged duringcargo test
will not be captured by the test harness by default.TheBuilder::is_test
method can be used in unit tests to ensure logs will be captured:
#[cfg(test)]modtests {uselog::info;fninit() {let _= env_logger::builder().is_test(true).try_init(); }#[test]fnit_works() { init();info!("This record will be captured by `cargo test`");assert_eq!(2,1+1); }}
Enabling test capturing comes at the expense of color and other style supportand may have performance implications.
§Disabling colors
Colors and other styles can be configured with theRUST_LOG_STYLE
environment variable. It accepts the following values:
auto
(default) will attempt to print style characters, but don’t force the issue.If the console isn’t available on Windows, or if TERM=dumb, for example, then don’t print colors.always
will always print style characters even if they aren’t supported by the terminal.This includes emitting ANSI colors on Windows if the console API is unavailable.never
will never print style characters.
§Tweaking the default format
Parts of the default format can be excluded from the log output using theBuilder
.The following example excludes the timestamp from the log output:
env_logger::builder() .format_timestamp(None) .init();
§Stability of the default format
The default format won’t optimise for long-term stability, and explicitly makes noguarantees about the stability of its output across major, minor or patch versionbumps during0.x
.
If you want to capture or interpret the output ofenv_logger
programmaticallythen you should use a custom format.
§Using a custom format
Custom formats can be provided as closures to theBuilder
.These closures take aFormatter
andlog::Record
as arguments:
usestd::io::Write;env_logger::builder() .format(|buf, record| {writeln!(buf,"{}: {}", record.level(), record.args()) }) .init();
See thefmt
module for more details about custom formats.
§Specifying defaults for environment variables
env_logger
can read configuration from environment variables.If these variables aren’t present, the default value to use can be tweaked with theEnv
type.The following example defaults to logwarn
and above if theRUST_LOG
environment variableisn’t set:
useenv_logger::Env;env_logger::Builder::from_env(Env::default().default_filter_or("warn")).init();
Re-exports§
pub use self::fmt::Target;
pub use self::fmt::TimestampPrecision;
pub use self::fmt::WriteStyle;
Modules§
- fmt
- Formatting for log records.
Structs§
- Builder
Builder
acts as builder for initializing aLogger
.- Env
- Set of environment variables to configure from.
- Logger
- The env logger.
Constants§
- DEFAULT_
FILTER_ ENV - The default name for the environment variable to read filters from.
- DEFAULT_
WRITE_ STYLE_ ENV - The default name for the environment variable to read style preferences from.
Functions§
- builder
- Create a new builder with the default environment variables.
- from_
env Deprecated - Create a builder from the given environment variables.
- init
- Initializes the global logger with an env logger.
- init_
from_ env - Initializes the global logger with an env logger from the given environmentvariables.
- try_
init - Attempts to initialize the global logger with an env logger.
- try_
init_ from_ env - Attempts to initialize the global logger with an env logger from the givenenvironment variables.