add: logger
This commit is contained in:
88
Cargo.lock
generated
88
Cargo.lock
generated
@@ -23,6 +23,15 @@ dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
@@ -308,7 +317,9 @@ version = "0.4.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||
dependencies = [
|
||||
"iana-time-zone",
|
||||
"num-traits",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -846,6 +857,30 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"core-foundation-sys",
|
||||
"iana-time-zone-haiku",
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone-haiku"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.4.0"
|
||||
@@ -2315,12 +2350,65 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.48.0"
|
||||
|
||||
@@ -17,7 +17,9 @@ panic = "abort"
|
||||
strip = "symbols"
|
||||
|
||||
[features]
|
||||
default = ["native-tls"]
|
||||
default = ["native-tls", "log-timestamp"]
|
||||
log-timestamp = ["chrono/clock"]
|
||||
|
||||
http2 = ["axum/http2"]
|
||||
http2-req = ["reqwest/http2"]
|
||||
# http3-req = ["reqwest/http3"] # experimental
|
||||
|
||||
3
justfile
3
justfile
@@ -19,7 +19,8 @@ preview data="data/test/aoc-response.json" \
|
||||
config="data/test/srv-config.toml" \
|
||||
port="8080":
|
||||
AOC_TEST_DATA="$(cat '{{ data }}')" \
|
||||
cargo run -- serve -c '{{ config }}' -l '[::]:{{ port }}'
|
||||
cargo run -- --log=trace \
|
||||
serve -c '{{ config }}' -l '[::]:{{ port }}'
|
||||
|
||||
release:
|
||||
RUSTFLAGS="\
|
||||
|
||||
@@ -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
51
src/log/fmt.rs
Normal 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
113
src/log/loglevel.rs
Normal 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
53
src/log/macros.rs
Normal 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
6
src/log/mod.rs
Normal 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
9
src/log/state.rs
Normal 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);
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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(¶ms).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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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??,
|
||||
|
||||
Reference in New Issue
Block a user