Daniel Fath
Daniel Fath

Reputation: 18059

Logging Rust programs

If we have following code

fn main() {
    error!("This is an error log")
    warn!("This is a warn log")
    info!("this is an info log")
    debug!("This is a debug log")
}

How do we enable the debug level output on Windows?

Upvotes: 18

Views: 22396

Answers (4)

jerome
jerome

Reputation: 341

I hope this is helpful for people. Below is my solution for using log. I wanted to turn on by default, instead of controlling log via environment variables.

Add this code before you issue log statements.

// enable logging, since log defaults to silent
std::env::set_var("RUST_LOG", "info");
env_logger::init();

...

debug!("LOGGING **************************");
info!("LOGGING **************************");
error!("LOGGING **************************");

Then, all of these will output to stdout.

Here are the log docs.

Upvotes: 3

rustyMagnet
rustyMagnet

Reputation: 4085

If you look at env_logger documentation it says:

"by default all logging is disabled except for the error level."

You set an ENVIRONMENT variable. In your case: RUST_LOG=debug.

extern crate env_logger;
extern crate log;
use log::{debug, error, info, warn};


fn main() {
    env_logger::init();

    error!("[!]  error");
    warn!("[!]   warn");
    info!("[!]   info");
    debug!("[!]  debug");
}

/*
[2021-08-19T13:14:15Z ERROR cliapp] [!]  error
[2021-08-19T13:14:15Z WARN  cliapp] [!]   warn
[2021-08-19T13:14:15Z INFO  cliapp] [!]   info
[2021-08-19T13:14:15Z DEBUG cliapp] [!]  debug
*/

CLion tip ->

enter image description here

Upvotes: 8

Pawan Bisht
Pawan Bisht

Reputation: 211

You can set the logging level in the program by setting them to your environment as well. The statement you have to write is:

RUST_LOG=YOUR-PROJECT-NAME=log_level

eg: RUST_LOG=Hello-World=info or RUST_LOG=Hello-World=3

After setting your log level the next step is to initialize them by using env_logger::init().

Upvotes: 3

Chris Morgan
Chris Morgan

Reputation: 90712

When executing your program, you need to set the RUST_LOG environment variable appropriately; it is (as far as this is concerned) a comma-separated key=value list; the keys are crate or module names, e.g. extra or std::option; the values are numbers, mapped to log levels:

  • 1: error
  • 2: warn
  • 3: info
  • 4: debug

(Each level includes the more significant levels.)

In Command Prompt, compiling and running myprog with showing warnings and errors would be something like:

rustc myprog.rs
set RUST_LOG=myprog=4
myprog.exe

Upvotes: 12

Related Questions