add: logger

This commit is contained in:
2026-11-24 21:48:45 +01:00
parent 01e38bb791
commit ba66bdb68a
12 changed files with 342 additions and 11 deletions

View File

@@ -55,6 +55,9 @@ pub mod typ {
#[command(version, about, long_about = None)]
#[command(styles = styles())]
pub struct Args {
#[arg(long, visible_alias = "log", default_value_t = Default::default(), value_enum)]
pub loglevel: crate::log::LogLevel,
/// Command
#[command(subcommand)]
pub command: Command,

51
src/log/fmt.rs Normal file
View File

@@ -0,0 +1,51 @@
use std::{
fmt,
io::{self, Write},
sync::atomic::Ordering as AOrd,
};
use crate::log::LogLevel;
use crate::log::state;
pub fn formatter(
out: &mut impl Write,
level: LogLevel,
args: fmt::Arguments<'_>,
// (file, ln, column)
#[cfg(debug_assertions)] extra_data: (&'static str, u32, u32),
) -> io::Result<()> {
if level < state::LOG_LEVEL.load(AOrd::Relaxed) {
return Ok(());
}
#[cfg(debug_assertions)]
let (f, l, c) = extra_data;
let style = level.get_default_style();
let args = {
#[cfg(debug_assertions)]
{
format_args!("[{style}{level:?}{style:#} {f}:{l}:{c}] {args}")
}
#[cfg(not(debug_assertions))]
if level == LogLevel::Info {
format_args!("{args}")
} else {
format_args!("{style}{level}:{style:#} {args}")
}
};
{
#[cfg(feature = "log-timestamp")]
{
let ts = anstyle::AnsiColor::Blue.on_default();
let now = chrono::Local::now().to_rfc3339();
writeln!(out, "{ts}{now}{ts:#} {args}")
}
#[cfg(not(feature = "log-timestamp"))]
{
writeln!(out, "{args}")
}
}
}

113
src/log/loglevel.rs Normal file
View File

@@ -0,0 +1,113 @@
use std::sync::atomic::{AtomicU8, Ordering};
use anstyle::{AnsiColor, Style};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, clap::ValueEnum)]
#[repr(u8)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warning,
Error,
}
impl std::fmt::Debug for LogLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Trace => write!(f, "{:<5}", "TRACE"),
Self::Debug => write!(f, "{:<5}", "DEBUG"),
Self::Info => write!(f, "{:<5}", "INFO"),
Self::Warning => write!(f, "{:<5}", "WARN"),
Self::Error => write!(f, "{:<5}", "ERROR"),
}
}
}
impl LogLevel {
pub const fn name(self) -> &'static str {
match self {
Self::Trace => "trace",
Self::Debug => "debug",
Self::Info => "info",
Self::Warning => "warning",
Self::Error => "error",
}
}
pub const fn get_default_style(self) -> Style {
// straight copied from log crate
match self {
Self::Trace => AnsiColor::Cyan.on_default(),
Self::Debug => AnsiColor::Blue.on_default(),
Self::Info => AnsiColor::Green.on_default(),
Self::Warning => AnsiColor::Yellow.on_default(),
Self::Error => AnsiColor::Red.on_default().bold(),
}
}
// pub fn from_name(s: &str) -> Option<Self> {
// match s {
// "trace" => Some(Self::Trace),
// "debug" => Some(Self::Debug),
// "info" => Some(Self::Info),
// "warning" => Some(Self::Warning),
// "error" => Some(Self::Error),
// _ => None,
// }
// }
pub const fn default_const() -> Self {
Self::Info
}
}
impl Default for LogLevel {
fn default() -> Self {
Self::default_const()
}
}
impl std::fmt::Display for LogLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
#[cfg(test)]
#[test]
fn log_ord() {
assert!(LogLevel::Error > LogLevel::Debug);
}
// INVARIANT: inner `u8` must always be a repr of a `LogLevel`
pub struct AtomicLogLevel(AtomicU8);
impl AtomicLogLevel {
/// # Safety
///
/// Safe as long as `b` is a repr of [`LogLevel`]
unsafe fn cast_as_level(b: u8) -> LogLevel {
unsafe { std::mem::transmute(b) }
}
pub fn load(&self, order: Ordering) -> LogLevel {
let r = self.0.load(order);
// SAFETY: `r` is a `LogLevel`
unsafe { Self::cast_as_level(r) }
}
pub fn store(&self, level: LogLevel, order: Ordering) {
self.0.store(level as u8, order);
}
pub const fn default_const() -> Self {
Self(AtomicU8::new(LogLevel::default_const() as u8))
}
}
impl Default for AtomicLogLevel {
fn default() -> Self {
Self::default_const()
}
}

53
src/log/macros.rs Normal file
View File

@@ -0,0 +1,53 @@
#![allow(unused_macros, unused_imports)]
macro_rules! stream {
(stdout) => {
std::io::stdout()
};
(stderr) => {
std::io::stderr()
};
}
pub(crate) use stream;
macro_rules! stream_msg {
(stdout) => {
"failed printing to stdout"
};
(stderr) => {
"failed printing to stderr"
};
}
pub(crate) use stream_msg;
macro_rules! build_macro {
( $d:tt; $vis:vis macro $name:ident on $stream:ident with $level:ident ) => {
// definition being a flat function call helps RA figure macro caller's shape
macro_rules! $name {
( $d($d arg:tt)* ) => {{
$crate::log::fmt::formatter(
&mut $crate::log::macros::stream!($stream),
$crate::log::LogLevel::$level,
::core::format_args!( $d($d arg)* ),
#[cfg(debug_assertions)]
// these are somehow resolved at the nested macro instead of on macro
// definition
(::core::file!(), ::core::line!(), ::core::column!()),
).expect($crate::log::macros::stream_msg!($stream))
}}
}
};
( $d:tt; $($vis:vis macro $name:ident on $stream:ident with $level:ident);* $(;)? ) => {
$( build_macro! { $d; $vis macro $name on $stream with $level } )*
};
}
build_macro! { $;
pub macro error on stderr with Error;
pub macro warn_ on stderr with Warning;
pub macro info on stderr with Info;
pub macro debug on stderr with Debug;
pub macro trace on stderr with Trace;
}
pub(crate) use {debug, error, info, trace, warn_ as warn};

6
src/log/mod.rs Normal file
View File

@@ -0,0 +1,6 @@
pub mod fmt;
pub mod loglevel;
pub mod macros;
pub mod state;
pub use loglevel::{AtomicLogLevel, LogLevel};

9
src/log/state.rs Normal file
View File

@@ -0,0 +1,9 @@
use std::sync::atomic::Ordering as AOrd;
use crate::log::{AtomicLogLevel, LogLevel};
pub static LOG_LEVEL: AtomicLogLevel = AtomicLogLevel::default_const();
pub fn set_log_level(level: LogLevel) {
LOG_LEVEL.store(level, AOrd::Relaxed);
}

View File

@@ -2,6 +2,7 @@ use clap::Parser as _;
mod args;
mod config;
mod log;
mod server;
mod consts {
@@ -10,6 +11,7 @@ mod consts {
fn main() -> anyhow::Result<()> {
let args = args::Args::parse();
log::state::set_log_level(args.loglevel);
match args.command {
args::Command::Serve {
@@ -20,7 +22,8 @@ fn main() -> anyhow::Result<()> {
let config = config::Config::open(config_path)?;
println!("{config:#?}");
#[cfg(debug_assertions)]
crate::log::macros::trace!("{config:#?}");
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()

View File

@@ -11,6 +11,8 @@ use tokio::{
time::Instant,
};
use crate::log::macros::{error, trace};
pub struct LeaderboardWatchedInfo {
expiry: DateTime<Utc>,
message: Result<String, String>,
@@ -26,7 +28,7 @@ impl LeaderboardState {
/// Censors an error so that it is fine to send it over the network without private information
/// risk. It also takes the time to log the original error itself.
fn censor_error(err: &reqwest::Error) -> String {
eprintln!("Leaderboard fetch failed: {err:?}");
error!("Leaderboard fetch failed: {err:?}");
let kind = if err.is_decode() {
"decode"
@@ -91,11 +93,11 @@ impl LeaderboardState {
loop {
tokio::time::sleep_until(next_expiry).await;
while sender.receiver_count() == 0 {
eprintln!("trace: receiver count is 0, idling...");
trace!("receiver count is 0, idling");
listener_attach_spawned.notified().await;
}
eprintln!("trace: updating cached object");
trace!("updating cached object");
let (new_expiry, new_params) = Self::fetch_params(&params).await;
next_expiry = new_expiry;
_ = sender.send_replace(new_params); // returns previous
@@ -143,7 +145,7 @@ pub async fn websocket(
};
if let Err(err) = socket.send(Message::Text(payload.into())).await {
eprintln!("ws error: {err}");
error!("web-socket error: {err}");
break;
}
@@ -159,11 +161,11 @@ pub async fn websocket(
Some(Ok(Message::Close(_))) | None => break,
Some(Ok(Message::Ping(_) | Message::Pong(_))) => {},
Some(Ok(Message::Text(_) | Message::Binary(_))) => {
eprintln!("received ws data, not our protocol");
error!("received web-socket data, not our protocol");
break;
},
Some(Err(err)) => {
eprintln!("ws receive error: {err}");
error!("web-socket receive error: {err}");
break;
}
}

View File

@@ -5,7 +5,7 @@ use itertools::Itertools;
use tokio::task::JoinSet;
use tower_http::services::ServeDir;
use crate::{args, config};
use crate::{args, config, log::macros::info};
mod api;
@@ -59,7 +59,7 @@ pub async fn run_server(mut args: ServeArgs, config: config::Config) -> anyhow::
}
}
println!("listening on: {}", args.listen.iter().format(", "));
info!("listening on: {}", args.listen.iter().format(", "));
match serves.join_next().await {
Some(res) => res??,