Struct env_logger::Builder

source ·
pub struct Builder { /* private fields */ }
Expand description

Builder acts as builder for initializing a Logger.

It can be used to customize the log format, change the environment variable used to provide the logging directives and also set the default log level filter.

§Examples

use env_logger::Builder;
use log::{LevelFilter, error, info};

let mut builder = Builder::from_default_env();

builder
    .format(|buf, record| writeln!(buf, "{} - {}", record.level(), record.args()))
    .filter(None, LevelFilter::Info)
    .init();

error!("error message");
info!("info message");

Implementations§

source§

impl Builder

source

pub fn new() -> Builder

Initializes the log builder with defaults.

NOTE: This method won’t read from any environment variables. Use the filter and write_style methods to configure the builder or use from_env or from_default_env instead.

§Examples

Create a new builder and configure filters and style:

use log::LevelFilter;
use env_logger::{Builder, WriteStyle};

let mut builder = Builder::new();

builder
    .filter(None, LevelFilter::Info)
    .write_style(WriteStyle::Always)
    .init();
Examples found in repository?
examples/filters_from_code.rs (line 10)
9
10
11
12
13
14
15
16
17
fn main() {
    Builder::new().filter_level(LevelFilter::max()).init();

    trace!("some trace log");
    debug!("some debug log");
    info!("some information log");
    warn!("some warning log");
    error!("some error log");
}
More examples
Hide additional examples
examples/direct_logger.rs (line 35)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fn main() {
    let stylish_logger = Builder::new()
        .filter(None, LevelFilter::Error)
        .write_style(WriteStyle::Always)
        .build();

    let unstylish_logger = Builder::new()
        .filter(None, LevelFilter::Error)
        .write_style(WriteStyle::Never)
        .build();

    stylish_logger.log(&record());
    unstylish_logger.log(&record());
}
source

pub fn from_env<'a, E>(env: E) -> Self
where E: Into<Env<'a>>,

Initializes the log builder from the environment.

The variables used to read configuration from can be tweaked before passing in.

§Examples

Initialise a logger reading the log filter from an environment variable called MY_LOG:

use env_logger::Builder;

let mut builder = Builder::from_env("MY_LOG");
builder.init();

Initialise a logger using the MY_LOG variable for filtering and MY_LOG_STYLE for whether or not to write styles:

use env_logger::{Builder, Env};

let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE");

let mut builder = Builder::from_env(env);
builder.init();
Examples found in repository?
examples/custom_default_format.rs (line 29)
24
25
26
27
28
29
30
31
32
33
fn init_logger() {
    let env = Env::default()
        .filter("MY_LOG_LEVEL")
        .write_style("MY_LOG_STYLE");

    Builder::from_env(env)
        .format_level(false)
        .format_timestamp_nanos()
        .init();
}
More examples
Hide additional examples
examples/custom_format.rs (line 31)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    fn init_logger() {
        let env = Env::default()
            .filter("MY_LOG_LEVEL")
            .write_style("MY_LOG_STYLE");

        Builder::from_env(env)
            .format(|buf, record| {
                // We are reusing `anstyle` but there are `anstyle-*` crates to adapt it to your
                // preferred styling crate.
                let warn_style = buf.default_level_style(log::Level::Warn);
                let timestamp = buf.timestamp();

                writeln!(
                    buf,
                    "My formatted log ({timestamp}): {warn_style}{}{warn_style:#}",
                    record.args()
                )
            })
            .init();
    }
source

pub fn parse_env<'a, E>(&mut self, env: E) -> &mut Self
where E: Into<Env<'a>>,

Applies the configuration from the environment.

This function allows a builder to be configured with default parameters, to be then overridden by the environment.

§Examples

Initialise a logger with filter level Off, then override the log filter from an environment variable called MY_LOG:

use log::LevelFilter;
use env_logger::Builder;

let mut builder = Builder::new();

builder.filter_level(LevelFilter::Off);
builder.parse_env("MY_LOG");
builder.init();

Initialise a logger with filter level Off, then use the MY_LOG variable to override filtering and MY_LOG_STYLE to override whether or not to write styles:

use log::LevelFilter;
use env_logger::{Builder, Env};

let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE");

let mut builder = Builder::new();
builder.filter_level(LevelFilter::Off);
builder.parse_env(env);
builder.init();
source

pub fn from_default_env() -> Self

Initializes the log builder from the environment using default variable names.

This method is a convenient way to call from_env(Env::default()) without having to use the Env type explicitly. The builder will use the default environment variables.

§Examples

Initialise a logger using the default environment variables:

use env_logger::Builder;

let mut builder = Builder::from_default_env();
builder.init();
source

pub fn parse_default_env(&mut self) -> &mut Self

Applies the configuration from the environment using default variable names.

This method is a convenient way to call parse_env(Env::default()) without having to use the Env type explicitly. The builder will use the default environment variables.

§Examples

Initialise a logger with filter level Off, then configure it using the default environment variables:

use log::LevelFilter;
use env_logger::Builder;

let mut builder = Builder::new();
builder.filter_level(LevelFilter::Off);
builder.parse_default_env();
builder.init();
source

pub fn format<F>(&mut self, format: F) -> &mut Self
where F: Fn(&mut Formatter, &Record<'_>) -> Result<()> + Sync + Send + 'static,

Sets the format function for formatting the log output.

This function is called on each record logged and should format the log record and output it to the given Formatter.

The format function is expected to output the string directly to the Formatter so that implementations can use the std::fmt macros to format and output without intermediate heap allocations. The default env_logger formatter takes advantage of this.

When the color feature is enabled, styling via ANSI escape codes is supported and the output will automatically respect Builder::write_style.

§Examples

Use a custom format to write only the log message:

use std::io::Write;
use env_logger::Builder;

let mut builder = Builder::new();

builder.format(|buf, record| writeln!(buf, "{}", record.args()));
Examples found in repository?
examples/custom_format.rs (lines 32-43)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    fn init_logger() {
        let env = Env::default()
            .filter("MY_LOG_LEVEL")
            .write_style("MY_LOG_STYLE");

        Builder::from_env(env)
            .format(|buf, record| {
                // We are reusing `anstyle` but there are `anstyle-*` crates to adapt it to your
                // preferred styling crate.
                let warn_style = buf.default_level_style(log::Level::Warn);
                let timestamp = buf.timestamp();

                writeln!(
                    buf,
                    "My formatted log ({timestamp}): {warn_style}{}{warn_style:#}",
                    record.args()
                )
            })
            .init();
    }
More examples
Hide additional examples
examples/syslog_friendly_format.rs (lines 6-20)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
    match std::env::var("RUST_LOG_STYLE") {
        Ok(s) if s == "SYSTEMD" => env_logger::builder()
            .format(|buf, record| {
                writeln!(
                    buf,
                    "<{}>{}: {}",
                    match record.level() {
                        log::Level::Error => 3,
                        log::Level::Warn => 4,
                        log::Level::Info => 6,
                        log::Level::Debug => 7,
                        log::Level::Trace => 7,
                    },
                    record.target(),
                    record.args()
                )
            })
            .init(),
        _ => env_logger::init(),
    };
}
source

pub fn default_format(&mut self) -> &mut Self

Use the default format.

This method will clear any custom format set on the builder.

source

pub fn format_level(&mut self, write: bool) -> &mut Self

Whether or not to write the level in the default format.

Examples found in repository?
examples/custom_default_format.rs (line 30)
24
25
26
27
28
29
30
31
32
33
fn init_logger() {
    let env = Env::default()
        .filter("MY_LOG_LEVEL")
        .write_style("MY_LOG_STYLE");

    Builder::from_env(env)
        .format_level(false)
        .format_timestamp_nanos()
        .init();
}
source

pub fn format_module_path(&mut self, write: bool) -> &mut Self

Whether or not to write the module path in the default format.

source

pub fn format_target(&mut self, write: bool) -> &mut Self

Whether or not to write the target in the default format.

source

pub fn format_indent(&mut self, indent: Option<usize>) -> &mut Self

Configures the amount of spaces to use to indent multiline log records. A value of None disables any kind of indentation.

source

pub fn format_timestamp( &mut self, timestamp: Option<TimestampPrecision> ) -> &mut Self

Configures if timestamp should be included and in what precision.

source

pub fn format_timestamp_secs(&mut self) -> &mut Self

Configures the timestamp to use second precision.

source

pub fn format_timestamp_millis(&mut self) -> &mut Self

Configures the timestamp to use millisecond precision.

source

pub fn format_timestamp_micros(&mut self) -> &mut Self

Configures the timestamp to use microsecond precision.

source

pub fn format_timestamp_nanos(&mut self) -> &mut Self

Configures the timestamp to use nanosecond precision.

Examples found in repository?
examples/custom_default_format.rs (line 31)
24
25
26
27
28
29
30
31
32
33
fn init_logger() {
    let env = Env::default()
        .filter("MY_LOG_LEVEL")
        .write_style("MY_LOG_STYLE");

    Builder::from_env(env)
        .format_level(false)
        .format_timestamp_nanos()
        .init();
}
source

pub fn format_suffix(&mut self, suffix: &'static str) -> &mut Self

Configures the end of line suffix.

source

pub fn format_key_values<F>(&mut self, format: F) -> &mut Self
where F: Fn(&mut Formatter, &dyn Source) -> Result<()> + Sync + Send + 'static,

Available on crate feature unstable-kv only.

Set the format for structured key/value pairs in the log record

With the default format, this function is called for each record and should format the structured key-value pairs as returned by log::Record::key_values.

The format function is expected to output the string directly to the Formatter so that implementations can use the std::fmt macros, similar to the main format function.

The default format uses a space to separate each key-value pair, with an “=” between the key and value.

source

pub fn filter_module(&mut self, module: &str, level: LevelFilter) -> &mut Self

Adds a directive to the filter for a specific module.

§Examples

Only include messages for info and above for logs in path::to::module:

use env_logger::Builder;
use log::LevelFilter;

let mut builder = Builder::new();

builder.filter_module("path::to::module", LevelFilter::Info);
source

pub fn filter_level(&mut self, level: LevelFilter) -> &mut Self

Adds a directive to the filter for all modules.

§Examples

Only include messages for info and above for logs globally:

use env_logger::Builder;
use log::LevelFilter;

let mut builder = Builder::new();

builder.filter_level(LevelFilter::Info);
Examples found in repository?
examples/filters_from_code.rs (line 10)
9
10
11
12
13
14
15
16
17
fn main() {
    Builder::new().filter_level(LevelFilter::max()).init();

    trace!("some trace log");
    debug!("some debug log");
    info!("some information log");
    warn!("some warning log");
    error!("some error log");
}
source

pub fn filter(&mut self, module: Option<&str>, level: LevelFilter) -> &mut Self

Adds filters to the logger.

The given module (if any) will log at most the specified level provided. If no module is provided then the filter will apply to all log messages.

§Examples

Only include messages for info and above for logs in path::to::module:

use env_logger::Builder;
use log::LevelFilter;

let mut builder = Builder::new();

builder.filter(Some("path::to::module"), LevelFilter::Info);
Examples found in repository?
examples/direct_logger.rs (line 36)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fn main() {
    let stylish_logger = Builder::new()
        .filter(None, LevelFilter::Error)
        .write_style(WriteStyle::Always)
        .build();

    let unstylish_logger = Builder::new()
        .filter(None, LevelFilter::Error)
        .write_style(WriteStyle::Never)
        .build();

    stylish_logger.log(&record());
    unstylish_logger.log(&record());
}
source

pub fn parse_filters(&mut self, filters: &str) -> &mut Self

Parses the directives string in the same form as the RUST_LOG environment variable.

See the module documentation for more details.

source

pub fn target(&mut self, target: Target) -> &mut Self

Sets the target for the log output.

Env logger can log to either stdout, stderr or a custom pipe. The default is stderr.

The custom pipe can be used to send the log messages to a custom sink (for example a file). Do note that direct writes to a file can become a bottleneck due to IO operation times.

§Examples

Write log message to stdout:

use env_logger::{Builder, Target};

let mut builder = Builder::new();

builder.target(Target::Stdout);
source

pub fn write_style(&mut self, write_style: WriteStyle) -> &mut Self

Sets whether or not styles will be written.

This can be useful in environments that don’t support control characters for setting colors.

§Examples

Never attempt to write styles:

use env_logger::{Builder, WriteStyle};

let mut builder = Builder::new();

builder.write_style(WriteStyle::Never);
Examples found in repository?
examples/direct_logger.rs (line 37)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fn main() {
    let stylish_logger = Builder::new()
        .filter(None, LevelFilter::Error)
        .write_style(WriteStyle::Always)
        .build();

    let unstylish_logger = Builder::new()
        .filter(None, LevelFilter::Error)
        .write_style(WriteStyle::Never)
        .build();

    stylish_logger.log(&record());
    unstylish_logger.log(&record());
}
source

pub fn parse_write_style(&mut self, write_style: &str) -> &mut Self

Parses whether or not to write styles in the same form as the RUST_LOG_STYLE environment variable.

See the module documentation for more details.

source

pub fn is_test(&mut self, is_test: bool) -> &mut Self

Sets whether or not the logger will be used in unit tests.

If is_test is true then the logger will allow the testing framework to capture log records rather than printing them to the terminal directly.

source

pub fn try_init(&mut self) -> Result<(), SetLoggerError>

Initializes the global logger with the built env logger.

This should be called early in the execution of a Rust program. Any log events that occur before initialization will be ignored.

§Errors

This function will fail if it is called more than once, or if another library has already initialized a global logger.

source

pub fn init(&mut self)

Initializes the global logger with the built env logger.

This should be called early in the execution of a Rust program. Any log events that occur before initialization will be ignored.

§Panics

This function will panic if it is called more than once, or if another library has already initialized a global logger.

Examples found in repository?
examples/custom_default_format.rs (line 32)
24
25
26
27
28
29
30
31
32
33
fn init_logger() {
    let env = Env::default()
        .filter("MY_LOG_LEVEL")
        .write_style("MY_LOG_STYLE");

    Builder::from_env(env)
        .format_level(false)
        .format_timestamp_nanos()
        .init();
}
More examples
Hide additional examples
examples/filters_from_code.rs (line 10)
9
10
11
12
13
14
15
16
17
fn main() {
    Builder::new().filter_level(LevelFilter::max()).init();

    trace!("some trace log");
    debug!("some debug log");
    info!("some information log");
    warn!("some warning log");
    error!("some error log");
}
examples/custom_format.rs (line 44)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    fn init_logger() {
        let env = Env::default()
            .filter("MY_LOG_LEVEL")
            .write_style("MY_LOG_STYLE");

        Builder::from_env(env)
            .format(|buf, record| {
                // We are reusing `anstyle` but there are `anstyle-*` crates to adapt it to your
                // preferred styling crate.
                let warn_style = buf.default_level_style(log::Level::Warn);
                let timestamp = buf.timestamp();

                writeln!(
                    buf,
                    "My formatted log ({timestamp}): {warn_style}{}{warn_style:#}",
                    record.args()
                )
            })
            .init();
    }
examples/syslog_friendly_format.rs (line 21)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
    match std::env::var("RUST_LOG_STYLE") {
        Ok(s) if s == "SYSTEMD" => env_logger::builder()
            .format(|buf, record| {
                writeln!(
                    buf,
                    "<{}>{}: {}",
                    match record.level() {
                        log::Level::Error => 3,
                        log::Level::Warn => 4,
                        log::Level::Info => 6,
                        log::Level::Debug => 7,
                        log::Level::Trace => 7,
                    },
                    record.target(),
                    record.args()
                )
            })
            .init(),
        _ => env_logger::init(),
    };
}
source

pub fn build(&mut self) -> Logger

Build an env logger.

The returned logger implements the Log trait and can be installed manually or nested within another logger.

Examples found in repository?
examples/direct_logger.rs (line 38)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fn main() {
    let stylish_logger = Builder::new()
        .filter(None, LevelFilter::Error)
        .write_style(WriteStyle::Always)
        .build();

    let unstylish_logger = Builder::new()
        .filter(None, LevelFilter::Error)
        .write_style(WriteStyle::Never)
        .build();

    stylish_logger.log(&record());
    unstylish_logger.log(&record());
}

Trait Implementations§

source§

impl Debug for Builder

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Builder

source§

fn default() -> Builder

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.