rust-lang / log

Logging implementation for Rust
https://docs.rs/log
Apache License 2.0
2.12k stars 248 forks source link

Setting the file/line shown in a log message #609

Closed bconn98 closed 7 months ago

bconn98 commented 7 months ago

Hello,

I am trailing running a rust based logger from C++. However, I noticed that the line file and number get generated from the rust code. That makes sense to me, however, I'm wondering if it's possible to override those values? It looks like the Record that holds this value is generated and owned by the log macro and doesn't have direct access by the user.

Thomasdezeeuw commented 7 months ago

I'm afraid you can't overwrite the file and line number using the macros, however you can build your own log record using log::RecordBuilder, you can view log_impl (the actual implementation) as an example.

bconn98 commented 7 months ago

Okay, yeah I was envisioning something similar to that with manually building the record and passing it along. Thanks Tom. I'll mess around with it.

bconn98 commented 7 months ago

Any suggestions for generating fmt::Arguments outside of the log macro?

Thomasdezeeuw commented 7 months ago

Can only be done using format_args!.

bconn98 commented 7 months ago

Yup, messed around with that extensively but hitting a wall on the temporary nature of the returned Arguments

Thomasdezeeuw commented 7 months ago

Yeah, best (or only) usage is passing it directly to Recordbuilder::args.

bconn98 commented 7 months ago

Yup while doing that I saw the temporary issue. FWIW, the note doesn't resolve the issue.

error[E0716]: temporary value dropped while borrowed
  --> src/lib.rs:49:15
   |
49 |         .args(format_args!("{}", msg))
   |               ^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
...
54 |         .line(Some(line));
   |                          - temporary value is freed at the end of this statement
55 |
56 |     logger().log(&builder.build());
   |                   ------- borrow later used here
   |
   = note: this error originates in the macro `format_args` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider using a `let` binding to create a longer lived value
   |
48 ~     let binding = format_args!("{}", msg);
49 ~     builder
50 ~         .args(binding)
   |
NobodyXu commented 7 months ago

You might want to move the builder to be inside logger.log(), format_args! contains temporary in the macro after expanded so it cannot be binded to a variable, only use as a temporary.