Using `format_args!()` and `log::Record::builder`

Hi, I'm working with the log crate, trying to manually create a log::Record using builder() (I can't use the logging macros here). The builder method takes a core::fmt::Arguments as the logging message, which I'm attempting to fill with a preformatted &str using format_args!("{}", preformatted_msg). How can I satisfy the borrow constraints here?

pub fn main() {
    let msg = "preformatted message";
    let fmt = format_args!("{}", msg);
    let rec = log::Record::builder().args(fmt).build();
    log::logger().log(&rec);
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0597]: borrowed value does not live long enough
 --> src/main.rs:3:28
  |
3 |     let fmt = format_args!("{}", msg);
  |                            ^^^^      - temporary value dropped here while still borrowed
  |                            |
  |                            temporary value does not live long enough
...
7 | }
  | - temporary value needs to live until here
  |
  = note: consider using a `let` binding to increase its lifetime

error: aborting due to previous error

For more information about this error, try `rustc --explain E0597`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

Looks like you have to use the output of format_args! in the same statement:

log::logger().log(
    &log::Record::builder().args(format_args!("{}", msg)).build());
2 Likes

That seems to work, thanks!

I'm running into a similar issue, but I can't put everything into one statement, because one of the calls to the builder is conditional.

This doesn't work either:

let mut builder = log::Record::builder();
builder.args(format_args!("{}", msg));
let record = builder.build();

See Rust Playground

What does work is:

let mut builder = log::Record::builder();
if some_condition() {
    /// call more stuff on builder
}
let record = builder.args(format_args!("{}", msg)).build();

In my case, that is ok, if a bit awkward. But if I wanted to use different arguments depending on some condition, I'm not sure what you would do.

It seems like this error is caused by the implementation of the format_args! macro itself.