implement duration logging

This commit is contained in:
soruh 2023-03-18 21:03:41 +01:00
parent e17547ad83
commit 01d8002393
4 changed files with 21 additions and 19 deletions

1
Cargo.lock generated
View File

@ -184,6 +184,7 @@ dependencies = [
"console-subscriber",
"futures",
"hyper",
"once_cell",
"serde",
"serde_json",
"time",

View File

@ -17,6 +17,7 @@ console-subscriber = { version = "0.1.8", optional = true }
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.16", features = ["time"] }
time = { version = "0.3.20", features = ["local-offset", "macros"] }
once_cell = "1.17.1"
[features]
default = ["debug_server"]

View File

@ -138,6 +138,11 @@ fn spawn<T: Send + 'static>(
.unwrap_or_else(|err| panic!("failed to spawn {name:?}: {err:?}"))
}
static TIME_ZONE_OFFSET: once_cell::sync::OnceCell<time::UtcOffset> =
once_cell::sync::OnceCell::new();
static TIME_FORMAT: once_cell::sync::OnceCell<OwnedFormatItem> = once_cell::sync::OnceCell::new();
fn main() -> anyhow::Result<()> {
let config = Arc::new(Config::load("config.json")?);
@ -145,7 +150,13 @@ fn main() -> anyhow::Result<()> {
panic!("no allowed ports");
}
let local_offset = time::UtcOffset::local_offset_at(time::OffsetDateTime::UNIX_EPOCH)?;
TIME_FORMAT.set(config.time_format.clone()).unwrap();
TIME_ZONE_OFFSET
.set(time::UtcOffset::local_offset_at(
time::OffsetDateTime::UNIX_EPOCH,
)?)
.unwrap();
tokio::runtime::Builder::new_multi_thread()
.enable_all()
@ -167,8 +178,8 @@ fn main() -> anyhow::Result<()> {
fmt::layer()
.with_target(false)
.with_timer(fmt::time::OffsetTime::new(
local_offset,
config.time_format.clone(),
*TIME_ZONE_OFFSET.get().unwrap(),
TIME_FORMAT.get().unwrap(),
))
.with_filter(filter::LevelFilter::from_level(config.log_level)),
)

View File

@ -17,7 +17,7 @@ use tracing::{error, info, warn};
use crate::{
packets::Packet, spawn, Config, Number, Port, UnixTimestamp, PORT_OWNERSHIP_TIMEOUT,
PORT_RETRY_TIME,
PORT_RETRY_TIME, TIME_FORMAT, TIME_ZONE_OFFSET,
};
#[derive(Default, Serialize, Deserialize)]
@ -66,22 +66,11 @@ fn duration_in_hours(duration: Duration) -> String {
fn format_instant(instant: Instant) -> String {
let when = duration_in_hours(instant.elapsed()) + " ago";
todo!();
#[cfg(feature = "chrono")]
let when = (|| -> anyhow::Result<_> {
use chrono::{Local, TimeZone};
let date = Local
.timestamp_opt(
(SystemTime::now().duration_since(UNIX_EPOCH)? - instant.elapsed())
.as_secs()
.try_into()?,
0,
)
.latest()
.ok_or(anyhow!("invalid update timestamp"))?
.format("%Y-%m-%d %H:%M:%S");
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)? - instant.elapsed();
let date = time::OffsetDateTime::from_unix_timestamp(timestamp.as_secs() as i64)?
.to_offset(*TIME_ZONE_OFFSET.get().unwrap())
.format(TIME_FORMAT.get().unwrap())?;
Ok(format!("{date} ({when})"))
})()