I use the standard log
module of rust. I'm trying to have a very simple logger that records all that is sent to it via debug!
, trace!
, etc. Then from time to time, I want to read these records and do something else with them. I had something like this in mind (I have removed useless code):
struct SimpleLogger {
records : Vec<String>
}
impl SimpleLogger {
fn dump(&mut self) {
for x in self.records.into_iter() {
println!("{}", x);
}
self.records.clear();
}
}
impl log::Log for SimpleLogger {
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
self.records.push(format!("{} - {}", record.level(), record.args()));
}
}
}
This is challenging for these reasons:
- Once the logger has been set as the global logger (using
log::set_logger
), I loose the ownership. So I can't calldump
anymore (because I don't have a reference to it anymore, it has been captured byset_logger
). - In the
Log
trait, thelog
method accepts a non mutable reference toself
. Therefore, I can't update the vector of records there.
I've checked other loggers and they seem to use Write
objects, but still it seems everything is thought to deliver the records and then throw them away. Moreover, it seems the loggers need to be thread safe so I'd have to use mutex...
How can I do ?