Merge pull request #12 from objz/stout/sterr-parse-tui
added minecraft log parser
This commit is contained in:
7 files changed
+661
-29
No files matched your search
Generated
+60
@@ -1053,6 +1053,15 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd2e7510819d6fbf51a5545c8f922716ecfb14df168a3242f7d33e0239efe6a1"
|
||||
|
||||
[[package]]
|
||||
name = "fast-strip-ansi"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3086ffd0a7160f58f988c74173a002e255da505a114e2f5425acb1eaab2b8ac"
|
||||
dependencies = [
|
||||
"vt-push-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.4.1"
|
||||
@@ -1244,6 +1253,16 @@ dependencies = [
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gdb-command"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73b2762e2f2c0768e1137b33e9f7cf31599994e96496f4e020cc16e0d4e66319"
|
||||
dependencies = [
|
||||
"regex",
|
||||
"wait-timeout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
@@ -1927,6 +1946,12 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kodama"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f868feceed4703c842925c14232667c5f29c8059d0354154b2d06ec3bf9daf82"
|
||||
|
||||
[[package]]
|
||||
name = "kqueue"
|
||||
version = "1.1.1"
|
||||
@@ -1977,6 +2002,19 @@ version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libcasr"
|
||||
version = "2.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "159cff1fadbb464709c30306774c57171e98cc1ea41e7767df5c63819743a453"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"gdb-command",
|
||||
"kodama",
|
||||
"regex",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
@@ -3167,8 +3205,10 @@ dependencies = [
|
||||
"crossterm 0.29.0",
|
||||
"dirs",
|
||||
"dirs-next",
|
||||
"fast-strip-ansi",
|
||||
"image",
|
||||
"insta",
|
||||
"libcasr",
|
||||
"log",
|
||||
"minecraft-msa-auth",
|
||||
"notify",
|
||||
@@ -3178,6 +3218,7 @@ dependencies = [
|
||||
"ratatui-image",
|
||||
"ratatui-textarea",
|
||||
"ratatui-themekit",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"rstest",
|
||||
"serde",
|
||||
@@ -4331,6 +4372,16 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
|
||||
|
||||
[[package]]
|
||||
name = "vt-push-parser"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdbf39d53c5a50cad8119d9cde929ecd208764e8d8d1626486b8929cbcd5f0e7"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vtparse"
|
||||
version = "0.6.2"
|
||||
@@ -4340,6 +4391,15 @@ dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wait-timeout"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
|
||||
@@ -58,6 +58,9 @@ open = "5"
|
||||
which = "8.0.2"
|
||||
dirs = "6.0.0"
|
||||
notify = "8"
|
||||
regex = "1"
|
||||
fast-strip-ansi = "0.13"
|
||||
libcasr = "2.13"
|
||||
|
||||
|
||||
[profile.release]
|
||||
|
||||
+91
-12
@@ -2,6 +2,7 @@
|
||||
// handles classpath assembly, auth token injection, and log capture.
|
||||
// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify).
|
||||
|
||||
pub(crate) mod parser;
|
||||
mod patches;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -580,63 +581,113 @@ pub async fn launch(
|
||||
use std::io::Write;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
use crate::instance::launch::parser::{LogStream, MinecraftLogParser};
|
||||
|
||||
let log_writer: Arc<Mutex<Option<std::fs::File>>> = Arc::new(Mutex::new(
|
||||
log_file_path.and_then(|p| std::fs::File::create(p).ok()),
|
||||
));
|
||||
|
||||
let (log_tx, mut log_rx) = mpsc::channel::<(LogStream, String)>(1024);
|
||||
let parser_name = name_for_task.clone();
|
||||
let parser_task = tokio::spawn(async move {
|
||||
let mut parser = MinecraftLogParser::new();
|
||||
let idle_flush = Duration::from_millis(150);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
maybe_line = log_rx.recv() => {
|
||||
match maybe_line {
|
||||
Some((stream, line)) => {
|
||||
for event in parser.push_line(stream, line) {
|
||||
emit_parsed_instance_log(&parser_name, event);
|
||||
}
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
_ = sleep(idle_flush), if parser.has_pending() => {
|
||||
if let Some(event) = parser.flush() {
|
||||
emit_parsed_instance_log(&parser_name, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(event) = parser.flush() {
|
||||
emit_parsed_instance_log(&parser_name, event);
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
let n = name_for_task.clone();
|
||||
let w = log_writer.clone();
|
||||
let tx = log_tx.clone();
|
||||
let mut lines = tokio::io::BufReader::new(stdout).lines();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
tracing::info!(target: "mc_instance", "[{}] {}", n, line);
|
||||
crate::instance_logs::push(&n, &line);
|
||||
if let Ok(mut f) = w.lock()
|
||||
&& let Some(f) = f.as_mut()
|
||||
{
|
||||
let _ = writeln!(f, "{}", line);
|
||||
}
|
||||
if tx.send((LogStream::Stdout, line)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
let n = name_for_task.clone();
|
||||
let w = log_writer.clone();
|
||||
let tx = log_tx.clone();
|
||||
let mut lines = tokio::io::BufReader::new(stderr).lines();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
tracing::warn!(target: "mc_instance", "[{}] {}", n, line);
|
||||
crate::instance_logs::push(&n, &line);
|
||||
if let Ok(mut f) = w.lock()
|
||||
&& let Some(f) = f.as_mut()
|
||||
{
|
||||
let _ = writeln!(f, "[STDERR] {}", line);
|
||||
let _ = writeln!(f, "{}", line);
|
||||
}
|
||||
if tx.send((LogStream::Stderr, line)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(log_tx);
|
||||
|
||||
// wait for either the process to exit naturally or a kill signal from the TUI
|
||||
let code = tokio::select! {
|
||||
let (code, killed_by_user) = tokio::select! {
|
||||
_ = kill_rx => {
|
||||
tracing::info!("[{}] Kill requested, terminating process", name_for_task);
|
||||
let _ = child.kill().await;
|
||||
let _ = child.wait().await;
|
||||
None
|
||||
(None, true)
|
||||
}
|
||||
result = child.wait() => {
|
||||
result.ok().and_then(|s| s.code())
|
||||
(result.ok().and_then(|s| s.code()), false)
|
||||
}
|
||||
};
|
||||
let _ = parser_task.await;
|
||||
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
|
||||
|
||||
if code == Some(0) {
|
||||
if code == Some(0) || killed_by_user {
|
||||
crate::running::remove(&name_for_task);
|
||||
} else {
|
||||
crate::running::set_state(&name_for_task, crate::running::RunState::Crashed(code));
|
||||
crate::tui::error_buffer::push_error(crate::tui::error_buffer::ErrorEvent {
|
||||
id: 0,
|
||||
level: tracing::Level::ERROR,
|
||||
message: match code {
|
||||
Some(code) => {
|
||||
format!("Minecraft '{name_for_task}' crashed with exit code {code}")
|
||||
}
|
||||
None => format!("Minecraft '{name_for_task}' crashed without an exit code"),
|
||||
},
|
||||
pushed_at: std::time::Instant::now(),
|
||||
});
|
||||
}
|
||||
|
||||
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
|
||||
@@ -654,6 +705,31 @@ pub async fn launch(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_parsed_instance_log(
|
||||
instance_name: &str,
|
||||
event: crate::instance::launch::parser::ParsedLogEvent,
|
||||
) {
|
||||
let text = event.lines.join("\n");
|
||||
match event.level {
|
||||
crate::instance::launch::parser::LogLevel::Error => {
|
||||
tracing::error!(target: "mc_instance", "[{}] {}", instance_name, text);
|
||||
}
|
||||
crate::instance::launch::parser::LogLevel::Warn => {
|
||||
tracing::warn!(target: "mc_instance", "[{}] {}", instance_name, text);
|
||||
}
|
||||
crate::instance::launch::parser::LogLevel::Info => {
|
||||
tracing::info!(target: "mc_instance", "[{}] {}", instance_name, text);
|
||||
}
|
||||
crate::instance::launch::parser::LogLevel::Debug => {
|
||||
tracing::debug!(target: "mc_instance", "[{}] {}", instance_name, text);
|
||||
}
|
||||
crate::instance::launch::parser::LogLevel::Trace => {
|
||||
tracing::trace!(target: "mc_instance", "[{}] {}", instance_name, text);
|
||||
}
|
||||
}
|
||||
crate::instance_logs::push_event(instance_name, event);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -817,7 +893,10 @@ mod tests {
|
||||
let result =
|
||||
migrate_legacy_loader_profile_if_needed(&profile_path, &modern, &config, &instance_dir)
|
||||
.await;
|
||||
assert!(matches!(result, Ok(None)), "expected Ok(None), got {result:?}");
|
||||
assert!(
|
||||
matches!(result, Ok(None)),
|
||||
"expected Ok(None), got {result:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
// live minecraft process log parser.
|
||||
//
|
||||
// disk launch logs stay raw, but the tui needs enough structure to color and
|
||||
// group output sanely. this parser keeps stdout/stderr as a hint, frames
|
||||
// multiline java/jvm/native bursts into events, then assigns a semantic level.
|
||||
|
||||
use libcasr::exception::Exception;
|
||||
use libcasr::java::{JavaException, JavaStacktrace};
|
||||
use libcasr::stacktrace::ParseStacktrace;
|
||||
use regex::Regex;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LogStream {
|
||||
Stdout,
|
||||
Stderr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LogLevel {
|
||||
Trace,
|
||||
Debug,
|
||||
Info,
|
||||
Warn,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct JavaParse {
|
||||
pub has_exception: bool,
|
||||
pub has_stacktrace: bool,
|
||||
pub stacktrace_frames: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ParsedLogEvent {
|
||||
pub level: LogLevel,
|
||||
pub primary_stream: LogStream,
|
||||
pub lines: Vec<String>,
|
||||
pub java: Option<JavaParse>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PendingEvent {
|
||||
level: LogLevel,
|
||||
primary_stream: LogStream,
|
||||
lines: Vec<String>,
|
||||
normalized_lines: Vec<String>,
|
||||
kind: EventKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum EventKind {
|
||||
Header,
|
||||
Java,
|
||||
JvmBurst,
|
||||
Native,
|
||||
Plain,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MinecraftLogParser {
|
||||
current: Option<PendingEvent>,
|
||||
minecraft_header_re: Regex,
|
||||
plain_level_re: Regex,
|
||||
java_exception_re: Regex,
|
||||
java_continuation_re: Regex,
|
||||
jvm_burst_re: Regex,
|
||||
native_header_re: Regex,
|
||||
}
|
||||
|
||||
impl Default for MinecraftLogParser {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl MinecraftLogParser {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
// header matching stays local because this parser is in the live
|
||||
// path; pulling in heavier pattern machinery would not help with
|
||||
// the multiline framing problem.
|
||||
minecraft_header_re: Regex::new(
|
||||
r"(?i)^\s*(?:\[[^\]]+\]\s*)*\[[^/\]]+/(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\]\s*:",
|
||||
)
|
||||
.expect("valid minecraft header regex"),
|
||||
plain_level_re: Regex::new(
|
||||
r"(?i)^\s*(?:\[[^\]]+\]\s*)*(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\b\s*(?:[:\]\-])?",
|
||||
)
|
||||
.expect("valid plain level regex"),
|
||||
java_exception_re: Regex::new(
|
||||
r"(?i)^\s*(?:Exception in thread .+|Caused by: |Suppressed: )?(?:[a-z_$][\w$]*\.)+(?:[A-Z][\w$]*(?:Exception|Error)|Throwable)(?::|\b)",
|
||||
)
|
||||
.expect("valid java exception regex"),
|
||||
java_continuation_re: Regex::new(
|
||||
r"^(?:\s+at\s+.+|\s*\.\.\.\s+\d+\s+more|Caused by:\s+.+|Suppressed:\s+.+)$",
|
||||
)
|
||||
.expect("valid java continuation regex"),
|
||||
jvm_burst_re: Regex::new(
|
||||
r"(?i)^\s*(?:Error:\s+.+|Unrecognized option:\s+.+|Could not create the Java Virtual Machine\.|A fatal exception has occurred\. Program will exit\.|Invalid maximum heap size:.+)$",
|
||||
)
|
||||
.expect("valid jvm burst regex"),
|
||||
native_header_re: Regex::new(r"^\[[A-Z]\]\s+\[[0-9:.]+\]\s+[^:]+:")
|
||||
.expect("valid native header regex"),
|
||||
current: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_line(&mut self, stream: LogStream, line: impl Into<String>) -> Vec<ParsedLogEvent> {
|
||||
let line = line.into();
|
||||
// classify against ansi-stripped text, but keep the original line for
|
||||
// display so the live log remains faithful to the child process.
|
||||
let normalized = fast_strip_ansi::strip_ansi_string(&line).into_owned();
|
||||
let analysis = self.analyze_line(stream, &normalized);
|
||||
|
||||
let Some(current) = &mut self.current else {
|
||||
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
// only hard starts split events. this keeps stacktraces and native
|
||||
// loader bursts together even when they arrive one line at a time.
|
||||
if should_split(current.kind, analysis.kind) {
|
||||
let finished = self.current.take().map(finish_event);
|
||||
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
|
||||
finished.into_iter().collect()
|
||||
} else {
|
||||
if analysis.level_priority() > current.level_priority() {
|
||||
current.level = analysis.level;
|
||||
}
|
||||
if matches!(current.kind, EventKind::Plain)
|
||||
&& !matches!(analysis.kind, EventKind::Plain)
|
||||
{
|
||||
current.kind = analysis.kind;
|
||||
}
|
||||
current.lines.push(line);
|
||||
current.normalized_lines.push(normalized);
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn flush(&mut self) -> Option<ParsedLogEvent> {
|
||||
self.current.take().map(finish_event)
|
||||
}
|
||||
|
||||
pub fn has_pending(&self) -> bool {
|
||||
self.current.is_some()
|
||||
}
|
||||
|
||||
fn analyze_line(&self, stream: LogStream, normalized: &str) -> LineAnalysis {
|
||||
if let Some(level) = self.header_level(normalized) {
|
||||
return LineAnalysis {
|
||||
level,
|
||||
kind: EventKind::Header,
|
||||
};
|
||||
}
|
||||
|
||||
if self.java_exception_re.is_match(normalized) {
|
||||
return LineAnalysis {
|
||||
level: LogLevel::Error,
|
||||
kind: EventKind::Java,
|
||||
};
|
||||
}
|
||||
|
||||
if self.java_continuation_re.is_match(normalized) {
|
||||
return LineAnalysis {
|
||||
level: LogLevel::Error,
|
||||
kind: EventKind::Java,
|
||||
};
|
||||
}
|
||||
|
||||
if self.jvm_burst_re.is_match(normalized) {
|
||||
return LineAnalysis {
|
||||
level: LogLevel::Error,
|
||||
kind: EventKind::JvmBurst,
|
||||
};
|
||||
}
|
||||
|
||||
if self.native_header_re.is_match(normalized) {
|
||||
return LineAnalysis {
|
||||
level: native_level(normalized).unwrap_or(LogLevel::Warn),
|
||||
kind: EventKind::Native,
|
||||
};
|
||||
}
|
||||
|
||||
LineAnalysis {
|
||||
level: match stream {
|
||||
LogStream::Stdout => LogLevel::Info,
|
||||
LogStream::Stderr => LogLevel::Error,
|
||||
},
|
||||
kind: EventKind::Plain,
|
||||
}
|
||||
}
|
||||
|
||||
fn header_level(&self, normalized: &str) -> Option<LogLevel> {
|
||||
self.minecraft_header_re
|
||||
.captures(normalized)
|
||||
.and_then(|caps| caps.name("level"))
|
||||
.or_else(|| {
|
||||
self.plain_level_re
|
||||
.captures(normalized)
|
||||
.and_then(|caps| caps.name("level"))
|
||||
})
|
||||
.and_then(|m| parse_level(m.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct LineAnalysis {
|
||||
level: LogLevel,
|
||||
kind: EventKind,
|
||||
}
|
||||
|
||||
impl LineAnalysis {
|
||||
fn level_priority(self) -> u8 {
|
||||
level_priority(self.level)
|
||||
}
|
||||
}
|
||||
|
||||
impl PendingEvent {
|
||||
fn new(stream: LogStream, line: String, normalized: String, analysis: LineAnalysis) -> Self {
|
||||
Self {
|
||||
level: analysis.level,
|
||||
primary_stream: stream,
|
||||
lines: vec![line],
|
||||
normalized_lines: vec![normalized],
|
||||
kind: analysis.kind,
|
||||
}
|
||||
}
|
||||
|
||||
fn level_priority(&self) -> u8 {
|
||||
level_priority(self.level)
|
||||
}
|
||||
}
|
||||
|
||||
fn should_split(current: EventKind, next: EventKind) -> bool {
|
||||
match next {
|
||||
EventKind::Header => true,
|
||||
EventKind::Native => !matches!(current, EventKind::Native),
|
||||
EventKind::JvmBurst => !matches!(current, EventKind::JvmBurst),
|
||||
EventKind::Java => !matches!(current, EventKind::Java | EventKind::Header),
|
||||
EventKind::Plain => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_event(mut event: PendingEvent) -> ParsedLogEvent {
|
||||
let normalized_body = event.normalized_lines.join("\n");
|
||||
// libcasr is intentionally second-stage here: first frame the multiline
|
||||
// event ourselves, then ask libcasr whether the block is a java failure.
|
||||
let java = parse_java(&normalized_body);
|
||||
|
||||
if java
|
||||
.as_ref()
|
||||
.is_some_and(|java| java.has_exception || java.has_stacktrace)
|
||||
{
|
||||
event.level = LogLevel::Error;
|
||||
}
|
||||
|
||||
ParsedLogEvent {
|
||||
level: event.level,
|
||||
primary_stream: event.primary_stream,
|
||||
lines: event.lines,
|
||||
java,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_java(body: &str) -> Option<JavaParse> {
|
||||
let stacktrace_entries = JavaStacktrace::extract_stacktrace(body).unwrap_or_default();
|
||||
let parsed_stacktrace = if stacktrace_entries.is_empty() {
|
||||
None
|
||||
} else {
|
||||
JavaStacktrace::parse_stacktrace(&stacktrace_entries).ok()
|
||||
};
|
||||
let has_exception = JavaException::parse_exception(body).is_some();
|
||||
let has_stacktrace = parsed_stacktrace
|
||||
.as_ref()
|
||||
.is_some_and(|stacktrace| !stacktrace.is_empty());
|
||||
|
||||
if has_exception || has_stacktrace {
|
||||
Some(JavaParse {
|
||||
has_exception,
|
||||
has_stacktrace,
|
||||
stacktrace_frames: parsed_stacktrace.map_or(0, |stacktrace| stacktrace.len()),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_level(level: &str) -> Option<LogLevel> {
|
||||
match level.to_ascii_uppercase().as_str() {
|
||||
"TRACE" => Some(LogLevel::Trace),
|
||||
"DEBUG" => Some(LogLevel::Debug),
|
||||
"INFO" => Some(LogLevel::Info),
|
||||
"WARN" => Some(LogLevel::Warn),
|
||||
"ERROR" | "FATAL" => Some(LogLevel::Error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn native_level(line: &str) -> Option<LogLevel> {
|
||||
match line.chars().nth(1)? {
|
||||
'E' | 'F' => Some(LogLevel::Error),
|
||||
'W' => Some(LogLevel::Warn),
|
||||
'I' => Some(LogLevel::Info),
|
||||
'D' => Some(LogLevel::Debug),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn level_priority(level: LogLevel) -> u8 {
|
||||
match level {
|
||||
LogLevel::Trace => 0,
|
||||
LogLevel::Debug => 1,
|
||||
LogLevel::Info => 2,
|
||||
LogLevel::Warn => 3,
|
||||
LogLevel::Error => 4,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_all(lines: &[(LogStream, &str)]) -> Vec<ParsedLogEvent> {
|
||||
let mut parser = MinecraftLogParser::new();
|
||||
let mut events = Vec::new();
|
||||
for (stream, line) in lines {
|
||||
events.extend(parser.push_line(*stream, *line));
|
||||
}
|
||||
events.extend(parser.flush());
|
||||
events
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_minecraft_headers() {
|
||||
let events = parse_all(&[
|
||||
(LogStream::Stdout, "[Render thread/INFO]: hello"),
|
||||
(LogStream::Stdout, "[Render thread/WARN]: careful"),
|
||||
(LogStream::Stdout, "[Render thread/ERROR]: broken"),
|
||||
(LogStream::Stdout, "[Render thread/DEBUG]: noisy"),
|
||||
(LogStream::Stdout, "[Render thread/TRACE]: tiny"),
|
||||
]);
|
||||
|
||||
assert_eq!(events.len(), 5);
|
||||
assert_eq!(events[0].level, LogLevel::Info);
|
||||
assert_eq!(events[1].level, LogLevel::Warn);
|
||||
assert_eq!(events[2].level, LogLevel::Error);
|
||||
assert_eq!(events[3].level, LogLevel::Debug);
|
||||
assert_eq!(events[4].level, LogLevel::Trace);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_stderr_info_stays_info() {
|
||||
let events = parse_all(&[(LogStream::Stderr, "[Render thread/INFO]: hello")]);
|
||||
|
||||
assert_eq!(events[0].level, LogLevel::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unstructured_stderr_falls_back_to_error() {
|
||||
let events = parse_all(&[(LogStream::Stderr, "native library failed")]);
|
||||
|
||||
assert_eq!(events[0].level, LogLevel::Error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_java_stacktrace() {
|
||||
let events = parse_all(&[
|
||||
(
|
||||
LogStream::Stderr,
|
||||
"Exception in thread \"main\" java.lang.RuntimeException: boom",
|
||||
),
|
||||
(
|
||||
LogStream::Stderr,
|
||||
"\tat net.minecraft.client.Main.main(Main.java:42)",
|
||||
),
|
||||
(
|
||||
LogStream::Stderr,
|
||||
"Caused by: java.lang.IllegalStateException: bad",
|
||||
),
|
||||
(LogStream::Stderr, "\tat example.Mod.load(Mod.java:7)"),
|
||||
(LogStream::Stdout, "[Render thread/INFO]: after"),
|
||||
]);
|
||||
|
||||
assert_eq!(events.len(), 2);
|
||||
assert_eq!(events[0].level, LogLevel::Error);
|
||||
assert_eq!(events[0].lines.len(), 4);
|
||||
assert!(
|
||||
events[0]
|
||||
.java
|
||||
.as_ref()
|
||||
.is_some_and(|java| java.has_stacktrace)
|
||||
);
|
||||
assert_eq!(events[1].level, LogLevel::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_jvm_startup_failure_burst() {
|
||||
let events = parse_all(&[
|
||||
(LogStream::Stderr, "Unrecognized option: --bad"),
|
||||
(
|
||||
LogStream::Stderr,
|
||||
"Could not create the Java Virtual Machine.",
|
||||
),
|
||||
(
|
||||
LogStream::Stderr,
|
||||
"A fatal exception has occurred. Program will exit.",
|
||||
),
|
||||
]);
|
||||
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].level, LogLevel::Error);
|
||||
assert_eq!(events[0].lines.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colored_header_classifies_but_keeps_original_text() {
|
||||
let line = "\u{1b}[31m[Render thread/ERROR]: red\u{1b}[0m";
|
||||
let events = parse_all(&[(LogStream::Stdout, line)]);
|
||||
|
||||
assert_eq!(events[0].level, LogLevel::Error);
|
||||
assert_eq!(events[0].lines[0], line);
|
||||
}
|
||||
}
|
||||
+36
-3
@@ -6,28 +6,61 @@ use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::instance::launch::parser::{LogLevel, LogStream, ParsedLogEvent};
|
||||
|
||||
const MAX_LINES: usize = 2000;
|
||||
|
||||
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<String>>>>;
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LiveLogLine {
|
||||
pub level: LogLevel,
|
||||
pub stream: LogStream,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<LiveLogLine>>>>;
|
||||
pub static LOGS: LazyLock<LogsMap> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
|
||||
|
||||
pub fn push(name: &str, line: impl Into<String>) {
|
||||
push_line(name, LogLevel::Info, LogStream::Stdout, line);
|
||||
}
|
||||
|
||||
pub fn push_event(name: &str, event: ParsedLogEvent) {
|
||||
for line in event.lines {
|
||||
push_line(name, event.level, event.primary_stream, line);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_line(name: &str, level: LogLevel, stream: LogStream, line: impl Into<String>) {
|
||||
if let Ok(mut logs) = LOGS.lock() {
|
||||
let buf = logs.entry(name.to_string()).or_insert_with(VecDeque::new);
|
||||
buf.push_back(line.into());
|
||||
buf.push_back(LiveLogLine {
|
||||
level,
|
||||
stream,
|
||||
text: line.into(),
|
||||
});
|
||||
while buf.len() > MAX_LINES {
|
||||
buf.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_all(name: &str) -> Vec<String> {
|
||||
pub fn get_entries(name: &str) -> Vec<LiveLogLine> {
|
||||
LOGS.lock()
|
||||
.ok()
|
||||
.and_then(|logs| logs.get(name).map(|buf| buf.iter().cloned().collect()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn get_all(name: &str) -> Vec<String> {
|
||||
LOGS.lock()
|
||||
.ok()
|
||||
.and_then(|logs| {
|
||||
logs.get(name)
|
||||
.map(|buf| buf.iter().map(|line| line.text.clone()).collect())
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn clear(name: &str) {
|
||||
if let Ok(mut logs) = LOGS.lock() {
|
||||
logs.remove(name);
|
||||
|
||||
+1
-1
@@ -121,7 +121,7 @@ impl<S: Subscriber> Layer<S> for StatusLayer {
|
||||
let now = chrono::Local::now().format("%H:%M:%S");
|
||||
push_app_log(format!("{now}:{level_str}:{target}: {}", visitor.message));
|
||||
|
||||
if level <= Level::WARN {
|
||||
if level <= Level::WARN && target != "mc_instance" {
|
||||
error_buffer::push_error(ErrorEvent {
|
||||
id: 0,
|
||||
level,
|
||||
|
||||
@@ -17,6 +17,7 @@ use ratatui::{
|
||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||
|
||||
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||
use crate::instance::launch::parser::LogLevel;
|
||||
use crate::instance::log_files::{LogFileEntry, read_log_file, scan_log_files};
|
||||
|
||||
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
|
||||
@@ -96,12 +97,7 @@ impl LogsState {
|
||||
}
|
||||
|
||||
pub fn drain_pending(&mut self) {
|
||||
// when the instance stops while viewing the live log, transition
|
||||
// to the on-disk log file so the viewer doesn't go blank
|
||||
let live_now = self.has_live();
|
||||
if self.was_live && !live_now && self.list_state.selected == Some(0) {
|
||||
self.load_selected_content();
|
||||
}
|
||||
self.was_live = live_now;
|
||||
|
||||
let taken = match self.pending.lock() {
|
||||
@@ -161,12 +157,15 @@ impl LogsState {
|
||||
});
|
||||
}
|
||||
|
||||
// when an instance is running, a synthetic "Live" entry is injected at index 0
|
||||
// when an instance is active or has just crashed, a synthetic "Live" entry
|
||||
// is injected at index 0 so parsed live log styling is retained.
|
||||
fn has_live(&self) -> bool {
|
||||
let name = self.loaded_for.as_deref().unwrap_or("");
|
||||
matches!(
|
||||
crate::running::get(name),
|
||||
Some(crate::running::RunState::Running) | Some(crate::running::RunState::Starting)
|
||||
Some(crate::running::RunState::Running)
|
||||
| Some(crate::running::RunState::Starting)
|
||||
| Some(crate::running::RunState::Crashed(_))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -515,16 +514,27 @@ fn render_viewer(
|
||||
let theme = THEME.as_ref();
|
||||
let is_live = has_live && state.list_state.selected == Some(0);
|
||||
|
||||
let all_lines: Vec<String> = if is_live {
|
||||
let all_lines: Vec<ViewerLine> = if is_live {
|
||||
let name = state.loaded_for.as_deref().unwrap_or("");
|
||||
crate::instance_logs::get_all(name)
|
||||
crate::instance_logs::get_entries(name)
|
||||
.into_iter()
|
||||
.map(|line| ViewerLine {
|
||||
text: line.text,
|
||||
level: Some(line.level),
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
state.viewer_lines.clone()
|
||||
state
|
||||
.viewer_lines
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|text| ViewerLine { text, level: None })
|
||||
.collect()
|
||||
};
|
||||
|
||||
let lines: Vec<&String> = all_lines
|
||||
let lines: Vec<&ViewerLine> = all_lines
|
||||
.iter()
|
||||
.filter(|l| state.viewer_search.matches(l))
|
||||
.filter(|l| state.viewer_search.matches(&l.text))
|
||||
.collect();
|
||||
|
||||
let visible_height = area.height as usize;
|
||||
@@ -548,7 +558,14 @@ fn render_viewer(
|
||||
.iter()
|
||||
.skip(state.viewer_scroll)
|
||||
.take(visible_height)
|
||||
.map(|line| search.highlight_line(line, line_level_style(line)))
|
||||
.map(|line| {
|
||||
search.highlight_line(
|
||||
&line.text,
|
||||
line.level
|
||||
.map(log_level_style)
|
||||
.unwrap_or_else(|| line_level_style(&line.text)),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
frame.render_widget(Paragraph::new(styled_lines), area);
|
||||
@@ -576,6 +593,21 @@ fn render_viewer(
|
||||
);
|
||||
}
|
||||
|
||||
struct ViewerLine {
|
||||
text: String,
|
||||
level: Option<LogLevel>,
|
||||
}
|
||||
|
||||
fn log_level_style(level: LogLevel) -> Style {
|
||||
let theme = THEME.as_ref();
|
||||
match level {
|
||||
LogLevel::Error => Style::default().fg(theme.error()),
|
||||
LogLevel::Warn => Style::default().fg(theme.warning()),
|
||||
LogLevel::Debug | LogLevel::Trace => Style::default().fg(theme.text_dim()),
|
||||
LogLevel::Info => Style::default().fg(theme.text()),
|
||||
}
|
||||
}
|
||||
|
||||
// color-code log lines by severity so errors actually stand out
|
||||
// instead of drowning in a wall of white text
|
||||
fn line_level_style(line: &str) -> Style {
|
||||
|
||||
Reference in new issue
Block a user