A simple logger configured via environment variables which writesto stdout or stderr, for use with the logging facade exposed by thelog
crate.
#[macro_use]externcratelog;externcrateenv_logger;uselog::Level;fnmain() {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.
Log levels are controlled on a per-module basis, and by default all loggingis disabled except forerror!
. Logging is controlled via theRUST_LOG
environment variable. The value of this environment variable is acomma-separated list of logging directives. A logging directive is of theform:
path::to::module=level
The path to the module is rooted in the name of the crate it was compiledfor, so if your program is contained in a filehello.rs
, for example, toturn on logging for this file you would use a value ofRUST_LOG=hello
.Furthermore, this path is a prefix-search, so all modules nested in thespecified module will also have logging enabled.
The actuallevel
is optional to specify. If omitted, all logging willbe enabled. If specified, it must be one of the stringsdebug
,error
,info
,warn
, ortrace
.
As the log level for a module is optional, the module to enable logging foris also optional. If only alevel
is provided, then the global loglevel for all modules is set to this value.
Some examples of valid values ofRUST_LOG
are:
hello
turns on all logging for the 'hello' moduleinfo
turns on all info logginghello=debug
turns on debug logging for 'hello'hello,std::option
turns on hello, and std's option loggingerror,hello=warn
turn on global error logging and also warn for helloARUST_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'.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 {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.
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.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() .default_format_timestamp(false) .init();
The default format won't optimise for long-term stability, and explicitly makes no guarantees about the stability of its output across major, minor or patch version bumps during0.x
.
If you want to capture or interpret the output ofenv_logger
programmatically then you should use 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.
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::from_env(Env::default().default_filter_or("warn")).init();
filter | Filtering for log records. |
fmt | Formatting for log records. |
Builder |
|
Env | Set of environment variables to configure from. |
Logger | The env logger. |
Target | Log target, either |
WriteStyle | Whether or not to print styles to the target. |
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. |
builder | Create a new builder with the default environment variables. |
from_env | 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. |
Prefix searches with a type followed by a colon (e.g.,fn:
) to restrict the search to a given type.
Accepted types are:fn
,mod
,struct
,enum
,trait
,type
,macro
, andconst
.
Search functions by type signature (e.g.,vec -> usize
or* -> vec
)
Search multiple things at once by splitting your query with comma (e.g.,str,u8
orString,struct:Vec,test
)