Skip to content
This repository has been archived by the owner on Jan 7, 2025. It is now read-only.

Handle failure of current_local_offset without panicking #15

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
Condure Changelog
=================

Unreleased

* If local time offset can't be determined, log timestamps as UTC instead of panicking.

v. 1.10.0 (2023-06-29)

* Add support for outgoing connections.
Expand Down
20 changes: 15 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const PRIVATE_SUBNETS: &[&str] = &[
];

struct SimpleLogger {
local_offset: UtcOffset,
local_offset: Option<UtcOffset>,
}

impl log::Log for SimpleLogger {
Expand All @@ -57,7 +57,7 @@ impl log::Log for SimpleLogger {
return;
}

let now = OffsetDateTime::now_utc().to_offset(self.local_offset);
let now = OffsetDateTime::now_utc().to_offset(self.local_offset.unwrap_or(UtcOffset::UTC));

let format = format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]"
Expand Down Expand Up @@ -90,15 +90,20 @@ impl log::Log for SimpleLogger {
fn flush(&self) {}
}

impl SimpleLogger {
pub(crate) fn offset_known(&self) -> bool {
self.local_offset.is_some()
}
}

static mut LOGGER: mem::MaybeUninit<SimpleLogger> = mem::MaybeUninit::uninit();

fn get_simple_logger() -> &'static SimpleLogger {
static INIT: Once = Once::new();

unsafe {
INIT.call_once(|| {
let local_offset =
UtcOffset::current_local_offset().expect("failed to get local time offset");
let local_offset = UtcOffset::current_local_offset().ok();

LOGGER.write(SimpleLogger { local_offset });
});
Expand Down Expand Up @@ -425,7 +430,8 @@ fn main() {
)
.get_matches();

log::set_logger(get_simple_logger()).unwrap();
let logger = get_simple_logger();
log::set_logger(logger).unwrap();

log::set_max_level(LevelFilter::Info);

Expand All @@ -450,6 +456,10 @@ fn main() {

log::set_max_level(level);

if !logger.offset_known() {
log::warn!("Failed to determine local time offset. Log timestamps will be in UTC.");
}

if *matches.get_one("sizes").unwrap() {
for (name, size) in condure::app::App::sizes() {
println!("{}: {} bytes", name, size);
Expand Down