Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you tackle the distinct tasks of logging HTTP requests and outputting trace and error messages deeper in your code?

I read this about how to perform logging of HTTP requests in Actix using logging middleware:

https://docs.rs/actix-web/1.0.0/actix_web/middleware/struct.Logger.html

Now say that I want to also add logging deep within my application using the log crate's framework. For example, I need detailed traces for debugging and a good place to output panic messages before the actual panic stops the world. Since only one logger can be configured via log, will this cause problems? If I want to also log the current username or session id down deep, do I have to pass it down all the way, or does Actix have a way to get at that globally?

like image 918
Paul Chernoch Avatar asked Oct 19 '25 02:10

Paul Chernoch


1 Answers

You can use the same logger for Actix-web and the rest of your application. The key is to distinguish the calls to the macros (trace!, debug!, info!, warn! and error!) by including the optional parameter target. Then you have to set the RUST_LOG environment variable.

Example invocation:

RUST_LOG="info,parser::expression=trace,actix_web=info" cargo run
  • The actix_web targets their code and prints the info and higher level messages.
  • The parser::expression targets a portion of my code and enables trace level messages.

In my code, here is a sample trace message:

    trace!(target: "parser::expression", "Tracing: {}", self.expression_source);

If you omit the target parameter, your module path becomes the default target, or so the docs say, but every spelling I have used for the module path, including more and fewer pieces, including the class name, etc, all fail, so I do not understand the docs. Specifying it manually does work, so that is what I do.

It is also important to setup the crate import correctly in the Cargo.toml file:

[dependencies]
log = { version = "0.4", features = ["max_level_trace", "release_max_level_warn", "std", "serde"] }

The above permits trace messages on the dev build, but only warnings on the release build. The compiler will discard the code at compile time, so changing the environment variable at run time will have no effect on this kind of change.

Here is some useful documentation:

https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log.html

like image 50
Paul Chernoch Avatar answered Oct 20 '25 19:10

Paul Chernoch