When I used tracing, I realized that the error! macro was pretty picky. What you tried to log had to have the Value trait. To get around that I did this:
if let Ok(formatted_xml) = formatter(&string) {
file.write_all(&*formatted_xml).unwrap_or_else(|error| {
let msg = error.to_string();
error!(msg, "Problem writing file: {}", msg);
});
};
Is that ok? From what I understand, I just made an allocation using to_string(). Am I right? I also see recommendations but about reducing allocations but I am not sure what is meant by that.
That's generally expected, since errors rarely implement any other form of serializing them.
Reducing allocations usually helps make code faster, but that applies to cases where the code is performance-sensitive (you're allocating millions of things), and/or where there are easy obvious ways to avoid allocations.
In this case the error handling code is on the less-used code path, and it's just one string.
That would be bad for a verbose! log where it often would be turned off and you're be doing the .to_string() for nothing. If it's something that deserves to be an error!, then presumably it's going to actually go somewhere, and thus as kornel said, it's fine.
For tracing's macros specifically, you can capture a value's Debug representation by writing ?error and Display by writing %error.
Separately, as a style thing, if you include something as structured data, you generally shouldn't also put it into the string message. Your current error! might potentially be logged as something like
ERROR: Problem writing file: access denied
.msg = "access denied"
(made up log syntax), and almost all tracing log sinks will record the structured data you give it, making its presence in the primary error message redundant.
I am not sure I follow about redundancy. Right now an example of the log file is like so:
{"v":0,"name":"ncclient","msg":"executing statement s184 with parameters: ["cfp2-or-qsfp28", "20-30-31-39-2d-30-37-38-2d-30-35-38-20-41-30-31-df-10-01-11-11-00-10-00-00-00-00-00-00-00-00", "FTLC9555REPM3-E5", "X6PB7T1", "1/1/c15", 2024-10-17T01:07:57.500683943Z, 5, "qsfp28-connector"]","level":20,"hostname":"87826decf1e2","pid":1,"time":"2024-10-17T01:07:57.533699616Z","target":"log","line":null,"file":null,"log.file":"/usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-postgres-0.7.12/src/query.rs","log.module_path":"tokio_postgres::query","log.target":"tokio_postgres::query","log.line":46}
{"v":0,"name":"ncclient","msg":"Database error: db error: ERROR: value too long for type character varying(60)","level":50,"hostname":"87826decf1e2","pid":1,"time":"2024-10-17T01:07:57.534173928Z","target":"vip_poll","line":230,"file":"src/main.rs"}