tools: file logger: avoid some possible unwraps in log method

writing to a file can explode quite easily.
time formatting to rfc3339 should be more robust, but it has a few
conditions where it could fail, so catch that too (and only really
do it if required).

The writes to stdout are left as is, it normally is redirected to
journal which is in memory, and thus breaks later than most stuff,
and at that point we probably do not care anymore anyway.

It could make sense to actually return a result here..

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
This commit is contained in:
Thomas Lamprecht 2020-11-02 19:26:59 +01:00
parent 3aade17125
commit 3cd529ea51

View File

@ -106,15 +106,21 @@ impl FileLogger {
stdout.write_all(b"\n").unwrap(); stdout.write_all(b"\n").unwrap();
} }
let now = proxmox::tools::time::epoch_i64();
let rfc3339 = proxmox::tools::time::epoch_to_rfc3339(now).unwrap();
let line = if self.options.prefix_time { let line = if self.options.prefix_time {
let now = proxmox::tools::time::epoch_i64();
let rfc3339 = match proxmox::tools::time::epoch_to_rfc3339(now) {
Ok(rfc3339) => rfc3339,
Err(_) => "1970-01-01T00:00:00Z".into(), // for safety, should really not happen!
};
format!("{}: {}\n", rfc3339, msg) format!("{}: {}\n", rfc3339, msg)
} else { } else {
format!("{}\n", msg) format!("{}\n", msg)
}; };
self.file.write_all(line.as_bytes()).unwrap(); if let Err(err) = self.file.write_all(line.as_bytes()) {
// avoid panicking, log methods should not do that
// FIXME: or, return result???
eprintln!("error writing to log file - {}", err);
}
} }
} }