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!