use std::backtrace::Backtrace;
use std::env;
use std::fmt::Write as _;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::panic::{self, PanicHookInfo};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
const MAX_LOG_DAYS: usize = 14;
const LOG_FILE_PREFIX: &str = "lune-";
const LOG_FILE_SUFFIX: &str = ".log";
const DEFAULT_FILTER: &str = "lune=info,wgpu=warn,naga=warn";
type SharedSink = Arc<Mutex<Option<LogSink>>>;
static LOG_SINK: OnceLock<SharedSink> = OnceLock::new();
#[derive(Clone, Debug, PartialEq, Eq)]
enum LogTarget {
Disabled,
FixedFile(PathBuf),
DailyDir(PathBuf),
}
#[derive(Clone, Debug)]
enum SinkMode {
FixedFile,
Daily { dir: PathBuf, max_days: usize },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct LocalTimestamp {
year: i32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
millis: u32,
utc_offset_minutes: Option<i32>,
}
impl LocalTimestamp {
fn date(self) -> (i32, u32, u32) {
(self.year, self.month, self.day)
}
fn format(self) -> String {
let mut out = String::with_capacity(32);
let _ = write!(
out,
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}",
self.year, self.month, self.day, self.hour, self.minute, self.second, self.millis
);
match self.utc_offset_minutes {
None => out.push('Z'),
Some(total_mins) => {
let sign = if total_mins >= 0 { '+' } else { '-' };
let abs = total_mins.unsigned_abs();
let _ = write!(out, "{sign}{:02}:{:02}", abs / 60, abs % 60);
}
}
out
}
}
struct LogSink {
mode: SinkMode,
current_date: (i32, u32, u32),
current_path: PathBuf,
file: File,
}
impl LogSink {
fn open(
target: LogTarget,
max_days: usize,
today: (i32, u32, u32),
) -> io::Result<Option<Self>> {
match target {
LogTarget::Disabled => Ok(None),
LogTarget::FixedFile(path) => {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent)?;
}
let file = open_append_file(&path)?;
Ok(Some(Self {
mode: SinkMode::FixedFile,
current_date: today,
current_path: path,
file,
}))
}
LogTarget::DailyDir(dir) => {
ensure_log_dir(&dir)?;
let path = dir.join(daily_filename(today));
let file = open_append_file(&path)?;
prune_old_daily_logs(&dir, max_days);
Ok(Some(Self {
mode: SinkMode::Daily { dir, max_days },
current_date: today,
current_path: path,
file,
}))
}
}
}
fn roll_to_date(&mut self, date: (i32, u32, u32)) -> io::Result<()> {
if date == self.current_date {
return Ok(());
}
let SinkMode::Daily { ref dir, max_days } = self.mode else {
return Ok(());
};
ensure_log_dir(dir)?;
let next_path = dir.join(daily_filename(date));
let next_file = open_append_file(&next_path)?;
self.file = next_file;
self.current_path = next_path;
self.current_date = date;
prune_old_daily_logs(dir, max_days);
Ok(())
}
fn write_entry(&mut self, date: (i32, u32, u32), bytes: &[u8]) {
if let Err(error) = self.roll_to_date(date) {
eprintln!("lune: failed to rotate daily log file: {error}");
}
if let Err(error) = self.file.write_all(bytes) {
eprintln!(
"lune: failed to write log entry to {}: {error}",
self.current_path.display()
);
}
}
fn flush(&mut self) {
let _ = self.file.flush();
}
}
struct LuneLogger {
stderr: env_logger::Logger,
sink: SharedSink,
}
impl log::Log for LuneLogger {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
self.stderr.enabled(metadata)
}
fn log(&self, record: &log::Record<'_>) {
if !self.enabled(record.metadata()) {
return;
}
self.stderr.log(record);
let mut guard = self
.sink
.lock()
.unwrap_or_else(|poison| poison.into_inner());
if let Some(sink) = guard.as_mut() {
let now = local_timestamp_now();
let line = format_log_line(now, std::process::id(), record);
sink.write_entry(now.date(), line.as_bytes());
}
}
fn flush(&self) {
self.stderr.flush();
let mut guard = self
.sink
.lock()
.unwrap_or_else(|poison| poison.into_inner());
if let Some(sink) = guard.as_mut() {
sink.flush();
}
}
}
pub fn init() {
let stderr =
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(DEFAULT_FILTER))
.format_timestamp_millis()
.build();
let max_level = stderr.filter();
let shared = LOG_SINK.get_or_init(|| Arc::new(Mutex::new(None))).clone();
let logger = Box::new(LuneLogger {
stderr,
sink: shared.clone(),
});
if log::set_boxed_logger(logger).is_ok() {
log::set_max_level(max_level);
install_panic_hook(shared);
}
}
pub(crate) fn configure(enabled: bool, config_dir: Option<&Path>) -> Option<PathBuf> {
let target = resolve_target(enabled, config_dir);
let today = local_timestamp_now().date();
let next_sink = match LogSink::open(target, MAX_LOG_DAYS, today) {
Ok(sink) => sink,
Err(error) => {
eprintln!("lune: could not open log file: {error}");
None
}
};
let next_path = next_sink.as_ref().map(|s| s.current_path.clone());
let shared = LOG_SINK.get_or_init(|| Arc::new(Mutex::new(None)));
let mut guard = shared.lock().unwrap_or_else(|poison| poison.into_inner());
if let Some(prev) = guard.as_mut() {
prev.flush();
}
*guard = next_sink;
next_path
}
pub fn active_log_path() -> Option<PathBuf> {
let shared = LOG_SINK.get()?;
let guard = shared.lock().unwrap_or_else(|poison| poison.into_inner());
guard.as_ref().map(|s| s.current_path.clone())
}
fn install_panic_hook(sink: SharedSink) {
let prev_hook = panic::take_hook();
panic::set_hook(Box::new(move |info| {
let now = local_timestamp_now();
let thread = std::thread::current();
let thread_name = thread.name().unwrap_or("unnamed");
let location = info
.location()
.map(|loc| format!("{}:{}:{}", loc.file(), loc.line(), loc.column()));
let payload = panic_payload(info);
let backtrace = Backtrace::force_capture();
let report = format_panic_report(
now,
std::process::id(),
thread_name,
&payload,
location.as_deref(),
&backtrace.to_string(),
);
{
let mut guard = sink.lock().unwrap_or_else(|poison| poison.into_inner());
if let Some(active) = guard.as_mut() {
active.write_entry(now.date(), report.as_bytes());
active.flush();
}
}
prev_hook(info);
}));
}
fn panic_payload(info: &PanicHookInfo<'_>) -> String {
if let Some(s) = info.payload().downcast_ref::<&str>() {
(*s).to_owned()
} else if let Some(s) = info.payload().downcast_ref::<String>() {
s.clone()
} else {
"<non-string panic payload>".to_owned()
}
}
fn format_log_line(ts: LocalTimestamp, pid: u32, record: &log::Record<'_>) -> String {
let target = if record.target().is_empty() {
"lune"
} else {
record.target()
};
format!(
"{} [pid={pid}] [{:<5}] {target}: {}\n",
ts.format(),
record.level(),
record.args()
)
}
fn format_panic_report(
ts: LocalTimestamp,
pid: u32,
thread_name: &str,
payload: &str,
location: Option<&str>,
backtrace: &str,
) -> String {
let loc = location.unwrap_or("<unknown>");
format!(
"{} [pid={pid}] [PANIC] thread '{thread_name}' panicked at {loc}: {payload}\nbacktrace:\n{backtrace}\n",
ts.format()
)
}
fn ensure_log_dir(dir: &Path) -> io::Result<()> {
fs::create_dir_all(dir)?;
let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
Ok(())
}
fn open_append_file(path: &Path) -> io::Result<File> {
OpenOptions::new()
.create(true)
.append(true)
.mode(0o600)
.open(path)
}
fn resolve_target(enabled: bool, config_dir: Option<&Path>) -> LogTarget {
resolve_target_with(
enabled,
config_dir,
env::var_os("LUNE_LOG_FILE").as_deref(),
env::var_os("LUNE_LOG_DIR").as_deref(),
env::var_os("XDG_STATE_HOME").as_deref(),
env::var_os("HOME").as_deref(),
&env::temp_dir(),
)
}
fn resolve_target_with(
enabled: bool,
config_dir: Option<&Path>,
log_file: Option<&std::ffi::OsStr>,
log_dir: Option<&std::ffi::OsStr>,
xdg_state_home: Option<&std::ffi::OsStr>,
home: Option<&std::ffi::OsStr>,
temp_dir: &Path,
) -> LogTarget {
if let Some(override_file) = log_file {
let text = override_file.to_string_lossy();
let trimmed = text.trim();
if trimmed.is_empty()
|| trimmed.eq_ignore_ascii_case("none")
|| trimmed.eq_ignore_ascii_case("off")
{
return LogTarget::Disabled;
}
return LogTarget::FixedFile(PathBuf::from(override_file));
}
if !enabled {
return LogTarget::Disabled;
}
if let Some(dir) = log_dir.filter(|v| !v.is_empty()) {
return LogTarget::DailyDir(PathBuf::from(dir));
}
if let Some(dir) = config_dir {
return LogTarget::DailyDir(dir.to_path_buf());
}
let state_base = if let Some(xdg) = xdg_state_home.filter(|v| !v.is_empty()) {
PathBuf::from(xdg)
} else if let Some(home) = home.filter(|v| !v.is_empty()) {
PathBuf::from(home).join(".local").join("state")
} else {
return LogTarget::DailyDir(temp_dir.join("lune-logs"));
};
LogTarget::DailyDir(state_base.join("lune").join("logs"))
}
fn daily_filename((year, month, day): (i32, u32, u32)) -> String {
format!("{LOG_FILE_PREFIX}{year:04}-{month:02}-{day:02}{LOG_FILE_SUFFIX}")
}
fn is_daily_log_name(name: &str) -> bool {
let Some(mid) = name
.strip_prefix(LOG_FILE_PREFIX)
.and_then(|s| s.strip_suffix(LOG_FILE_SUFFIX))
else {
return false;
};
let bytes = mid.as_bytes();
bytes.len() == 10
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& bytes[0..4].iter().all(u8::is_ascii_digit)
&& bytes[5..7].iter().all(u8::is_ascii_digit)
&& bytes[8..10].iter().all(u8::is_ascii_digit)
}
fn prune_old_daily_logs(dir: &Path, max_days: usize) {
if max_days == 0 {
return;
}
let Ok(entries) = fs::read_dir(dir) else {
return;
};
let mut names: Vec<String> = entries
.flatten()
.filter_map(|entry| {
let name = entry.file_name().into_string().ok()?;
is_daily_log_name(&name).then_some(name)
})
.collect();
if names.len() <= max_days {
return;
}
names.sort();
let remove_count = names.len() - max_days;
for old_name in &names[..remove_count] {
let _ = fs::remove_file(dir.join(old_name));
}
}
fn local_timestamp_now() -> LocalTimestamp {
timestamp_from_system_time(SystemTime::now())
}
fn timestamp_from_system_time(time: SystemTime) -> LocalTimestamp {
let duration = time.duration_since(UNIX_EPOCH).unwrap_or_default();
let secs_u64 = duration.as_secs();
let millis = duration.subsec_millis();
if let Ok(time_t) = libc::time_t::try_from(secs_u64) {
let local_tm = unsafe {
let mut tm = std::mem::zeroed::<libc::tm>();
let ptr = libc::localtime_r(&time_t, &mut tm);
(!ptr.is_null()).then_some(tm)
};
if let Some(tm) = local_tm {
let year = tm.tm_year + 1900;
let month = u32::try_from(tm.tm_mon + 1).unwrap_or(1);
let day = u32::try_from(tm.tm_mday).unwrap_or(1);
let hour = u32::try_from(tm.tm_hour).unwrap_or(0);
let minute = u32::try_from(tm.tm_min).unwrap_or(0);
let second = u32::try_from(tm.tm_sec.clamp(0, 60)).unwrap_or(0);
let offset_mins = i32::try_from(tm.tm_gmtoff / 60).ok();
return LocalTimestamp {
year,
month,
day,
hour,
minute,
second,
millis,
utc_offset_minutes: offset_mins,
};
}
}
utc_timestamp(secs_u64, millis)
}
fn utc_timestamp(epoch_secs: u64, millis: u32) -> LocalTimestamp {
let days = (epoch_secs / 86_400) as i64;
let secs_of_day = (epoch_secs % 86_400) as u32;
let (year, month, day) = civil_from_days(days);
LocalTimestamp {
year: year as i32,
month,
day,
hour: secs_of_day / 3_600,
minute: (secs_of_day % 3_600) / 60,
second: secs_of_day % 60,
millis,
utc_offset_minutes: None,
}
}
fn civil_from_days(days_since_epoch: i64) -> (i64, u32, u32) {
let z = days_since_epoch + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = mp + if mp < 10 { 3 } else { -9 };
let year = y + i64::from(m <= 2);
(year, m as u32, d as u32)
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use std::sync::atomic::{AtomicU64, Ordering};
use super::*;
static TEMP_SEQ: AtomicU64 = AtomicU64::new(1);
fn unique_temp_dir(label: &str) -> PathBuf {
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
env::temp_dir().join(format!("lune-log-{label}-{}-{seq}", std::process::id()))
}
#[test]
fn resolves_log_target_from_overrides_xdg_and_home() {
let tmp = Path::new("/tmp");
assert_eq!(
resolve_target_with(
false,
None,
None,
None,
Some(OsStr::new("/state")),
None,
tmp
),
LogTarget::Disabled
);
assert_eq!(
resolve_target_with(
true,
Some(Path::new("/custom/logs")),
None,
None,
Some(OsStr::new("/state")),
None,
tmp
),
LogTarget::DailyDir(PathBuf::from("/custom/logs"))
);
assert_eq!(
resolve_target_with(true, None, Some(OsStr::new("off")), None, None, None, tmp),
LogTarget::Disabled
);
assert_eq!(
resolve_target_with(true, None, Some(OsStr::new("")), None, None, None, tmp),
LogTarget::Disabled
);
assert_eq!(
resolve_target_with(
true,
Some(Path::new("/custom/logs")),
Some(OsStr::new("/tmp/custom.log")),
None,
None,
None,
tmp
),
LogTarget::FixedFile(PathBuf::from("/tmp/custom.log"))
);
assert_eq!(
resolve_target_with(
true,
Some(Path::new("/custom/logs")),
None,
Some(OsStr::new("/var/log/lune")),
None,
None,
tmp
),
LogTarget::DailyDir(PathBuf::from("/var/log/lune"))
);
assert_eq!(
resolve_target_with(
true,
None,
None,
None,
Some(OsStr::new("/state")),
Some(OsStr::new("/users/alice")),
tmp
),
LogTarget::DailyDir(PathBuf::from("/state/lune/logs"))
);
assert_eq!(
resolve_target_with(
true,
None,
None,
None,
None,
Some(OsStr::new("/users/alice")),
tmp
),
LogTarget::DailyDir(PathBuf::from("/users/alice/.local/state/lune/logs"))
);
assert_eq!(
resolve_target_with(true, None, None, None, None, None, tmp),
LogTarget::DailyDir(PathBuf::from("/tmp/lune-logs"))
);
}
#[test]
fn formats_timestamps_with_offset_and_milliseconds() {
let utc = utc_timestamp(0, 42);
assert_eq!(utc.format(), "1970-01-01T00:00:00.042Z");
let leap = utc_timestamp(1_709_210_096, 7);
assert_eq!(leap.format(), "2024-02-29T12:34:56.007Z");
let plus_eight = LocalTimestamp {
utc_offset_minutes: Some(8 * 60),
..leap
};
assert_eq!(plus_eight.format(), "2024-02-29T12:34:56.007+08:00");
}
#[test]
fn rolls_over_daily_files_and_prunes_oldest_beyond_retention() {
let dir = unique_temp_dir("daily");
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("keep-me.txt"), b"unrelated").unwrap();
let mut sink = LogSink::open(LogTarget::DailyDir(dir.clone()), 2, (2026, 11, 27))
.unwrap()
.unwrap();
sink.write_entry((2026, 11, 27), b"day1\n");
sink.write_entry((2026, 11, 28), b"day2\n");
sink.write_entry((2026, 11, 29), b"day3\n");
sink.flush();
assert!(!dir.join("lune-2026-11-27.log").exists());
assert_eq!(
fs::read_to_string(dir.join("lune-2026-11-28.log")).unwrap(),
"day2\n"
);
assert_eq!(
fs::read_to_string(dir.join("lune-2026-11-29.log")).unwrap(),
"day3\n"
);
assert!(dir.join("keep-me.txt").exists());
assert!(is_daily_log_name("lune-2026-11-29.log"));
assert!(!is_daily_log_name("lune.log"));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn formats_panic_report_with_location_and_payload() {
let ts = LocalTimestamp {
year: 2026,
month: 11,
day: 29,
hour: 0,
minute: 25,
second: 1,
millis: 123,
utc_offset_minutes: Some(480),
};
let report = format_panic_report(
ts,
42,
"main",
"surface lost",
Some("app/src/desktop.rs:100:5"),
"0: frame_zero",
);
assert!(report.contains("2026-11-29T00:25:01.123+08:00 [pid=42] [PANIC]"));
assert!(
report.contains("thread 'main' panicked at app/src/desktop.rs:100:5: surface lost")
);
assert!(report.contains("backtrace:\n0: frame_zero\n"));
}
}