Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make it clear and visible in the documentation that the evaluation of side effects depends on the logger #556

Closed
crumblingstatue opened this issue Apr 14, 2023 · 1 comment · Fixed by #620

Comments

@crumblingstatue
Copy link

crumblingstatue commented Apr 14, 2023

let mut foo = 0;
log::trace!("{:?}", foo += 1);
foo

This results in foo being 0, because foo += 1 wasn't evaluated.

env_logger::builder()
        .filter_level(log::LevelFilter::Trace)
        .init();
let mut foo = 0;
log::trace!("{:?}", foo += 1);
foo

This will evaluate the side effect, because the logger was initialized.

This behavior can be surprising, and can cause bugs during prototyping, when the user might try
to embed expressions with side effects inside log macro invocations, to log their results for debugging purposes.
If the logger isn't initialized (for example in a unit test), the side effects will not be evaluated and the behavior will be different than intended.

It should be made clear and prominently visible in the documentation that side effects inside log macro invocations might not be evaluated, depending on the logger's configuration, and so the user shouldn't write expressions with intended side effects inside log macro invocations.

I personally tried to log the result of creating a directory, like so

log::info!("{:?}", std::fs::create_dir("foo"));

And I was surprised when the directory wasn't created when the logger wasn't initialized.

@KodrAus
Copy link
Contributor

KodrAus commented Apr 19, 2023

It should be made clear and prominently visible in the documentation that side effects inside log macro invocations might not be evaluated, depending on the logger's configuration, and so the user shouldn't write expressions with intended side effects inside log macro invocations.

I think that's fair to call out 👍 We could state it as simply as "Avoid writing expressions with side-effects in log statements. They may not be evaluated".

EFanZh pushed a commit to EFanZh/log that referenced this issue Jul 23, 2023
so that release-pr can operate on them and increase minor version for a
new release.

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants