HarryRybacki / rust_developer

Homework and projects from Rust Developer course
0 stars 0 forks source link

Logging in shared library smells bad: #6

Closed HarryRybacki closed 1 month ago

HarryRybacki commented 1 month ago

In order to log output in the shared library, I must first instantiate the logger. IIUC this requires adding a main() as I've done here.

Adding a main.rs in this way, for this reason, smells bad. I'm unsure what the "Rusty" approach is e.g.: Refactor shared library to not need any logged output, instantiate the logger somewhere else e.g: in lib.rs, or to this is actually find and to leave it as is.

HarryRybacki commented 1 month ago

@luciusmagn what are your thoughts?

luciusmagn commented 1 month ago

The way that log and tracing are meant to be used in libraries is that you just produce messages, but do not instantiate a logger.

When you then use the library in a binary crate, the binary crate will instatiate the global logger itself, which will work even for log messages produced in the library.

The only exception is tests and examples, where you may want to instatiate a logger within the library. For tests, you need to use something like Once, since the order is not deterministic and they run in parallel.

The examples have a main() function and access to dev-dependencies, where you can add a logger implementation

HarryRybacki commented 1 month ago

Thanks @luciusmagn ! I must be missing how to instantiate this globally in that case. Both the Client and Server are binaries, pulling from common/lib.rs library. I removed common/main.rs and relaunched the apps. Sending messages was successful but the logger inside of common/lib.rs::send_message() for example still isn't activating...

HarryRybacki commented 1 month ago

Got it figured out. Things were working correctly as expected, I just didn't have the correct log level to see the outputs I was expecting.