Rocket - logging in the web application

log logging debug! info! warn! error! Rocket web

We can use println and eprintln in the Rocket-based code, but it is much better to use the logging facilities of Rocket. I think.

Dependencies

Nothing fancy. We use Rocket.

examples/rocket/logging/Cargo.toml

[package]
name = "logging"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rocket = "0.5"

The code

This is just a plain Hello World! application with Rocket. I did not even include the tests.

examples/rocket/logging/src/main.rs

#[macro_use]
extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    rocket::debug!("Debug from Hello World");
    rocket::info!("Info from Hello World");
    rocket::warn!("Warning from Hello World");
    rocket::error!("Error from Hello World");
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}


There are 4 macros we can use right from the rocket namespace:

rocket::debug!
rocket::info!
rocket::warn!
rocket::error!

We can run the application with cargo run and then when visit the web site at http://localhost:8000/ we will see the log messages on the console:

But oh, we only see the info, warn, and error messages. We don't see the debug message.

Configuring the log level

Rocket allows us to configure many things in the Rocket.toml file.

So I created it and added an entry to change the default normal level to debug.

examples/rocket/logging/Rocket.toml

[debug]
#log_level = "normal"
log_level = "debug"

Restarted the application and visited the web-site again.

This time I also saw the "debug" log message, but there was a lot of other output as Rocket printed both the whole Request and the whole Response struct.

I guess for now I stick with info!.

Related Pages

Rocket - web development with Rust
Rocket - access custom configuration in the routes

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo