forked from rtk-ai/rtk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_cmd.rs
More file actions
252 lines (218 loc) · 7.71 KB
/
Copy pathlog_cmd.rs
File metadata and controls
252 lines (218 loc) · 7.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use crate::tracking;
use anyhow::Result;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::fs;
use std::io::{self, BufRead};
use std::path::Path;
lazy_static! {
static ref TIMESTAMP_RE: Regex =
Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap();
static ref UUID_RE: Regex =
Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
.unwrap();
static ref HEX_RE: Regex = Regex::new(r"0x[0-9a-fA-F]+").unwrap();
static ref NUM_RE: Regex = Regex::new(r"\b\d{4,}\b").unwrap();
static ref PATH_RE: Regex = Regex::new(r"/[\w./\-]+").unwrap();
}
/// Filter and deduplicate log output
pub fn run_file(file: &Path, verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
eprintln!("Analyzing log: {}", file.display());
}
let content = fs::read_to_string(file)?;
let result = analyze_logs(&content);
println!("{}", result);
timer.track(
&format!("cat {}", file.display()),
"rtk log",
&content,
&result,
);
Ok(())
}
/// Filter logs from stdin
pub fn run_stdin(_verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut content = String::new();
let stdin = io::stdin();
for line in stdin.lock().lines() {
content.push_str(&line?);
content.push('\n');
}
let result = analyze_logs(&content);
println!("{}", result);
timer.track("log (stdin)", "rtk log (stdin)", &content, &result);
Ok(())
}
/// For use by other modules
pub fn run_stdin_str(content: &str) -> String {
analyze_logs(content)
}
fn analyze_logs(content: &str) -> String {
let mut result = Vec::new();
let mut error_counts: HashMap<String, usize> = HashMap::new();
let mut warn_counts: HashMap<String, usize> = HashMap::new();
let mut info_counts: HashMap<String, usize> = HashMap::new();
let mut unique_errors: Vec<String> = Vec::new();
let mut unique_warnings: Vec<String> = Vec::new();
// Use module-level lazy_static regexes for normalization
for line in content.lines() {
let line_lower = line.to_lowercase();
// Normalize for deduplication
let normalized =
normalize_log_line(line, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE);
// Categorize
if line_lower.contains("error")
|| line_lower.contains("fatal")
|| line_lower.contains("panic")
{
let count = error_counts.entry(normalized.clone()).or_insert(0);
if *count == 0 {
unique_errors.push(line.to_string());
}
*count += 1;
} else if line_lower.contains("warn") {
let count = warn_counts.entry(normalized.clone()).or_insert(0);
if *count == 0 {
unique_warnings.push(line.to_string());
}
*count += 1;
} else if line_lower.contains("info") {
*info_counts.entry(normalized).or_insert(0) += 1;
}
}
// Summary
let total_errors: usize = error_counts.values().sum();
let total_warnings: usize = warn_counts.values().sum();
let total_info: usize = info_counts.values().sum();
result.push("Log Summary".to_string());
result.push(format!(
" [error] {} errors ({} unique)",
total_errors,
error_counts.len()
));
result.push(format!(
" [warn] {} warnings ({} unique)",
total_warnings,
warn_counts.len()
));
result.push(format!(" [info] {} info messages", total_info));
result.push(String::new());
// Errors with counts
if !unique_errors.is_empty() {
result.push("[ERRORS]".to_string());
// Sort by count
let mut error_list: Vec<_> = error_counts.iter().collect();
error_list.sort_by(|a, b| b.1.cmp(a.1));
for (normalized, count) in error_list.iter().take(10) {
// Find original message
let original = unique_errors
.iter()
.find(|e| {
&normalize_log_line(e, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE)
== *normalized
})
.map(|s| s.as_str())
.unwrap_or(normalized);
let truncated = if original.len() > 100 {
let t: String = original.chars().take(97).collect();
format!("{}...", t)
} else {
original.to_string()
};
if **count > 1 {
result.push(format!(" [×{}] {}", count, truncated));
} else {
result.push(format!(" {}", truncated));
}
}
if error_list.len() > 10 {
result.push(format!(
" ... +{} more unique errors",
error_list.len() - 10
));
}
result.push(String::new());
}
// Warnings with counts
if !unique_warnings.is_empty() {
result.push("[WARNINGS]".to_string());
let mut warn_list: Vec<_> = warn_counts.iter().collect();
warn_list.sort_by(|a, b| b.1.cmp(a.1));
for (normalized, count) in warn_list.iter().take(5) {
let original = unique_warnings
.iter()
.find(|w| {
&normalize_log_line(w, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE)
== *normalized
})
.map(|s| s.as_str())
.unwrap_or(normalized);
let truncated = if original.len() > 100 {
let t: String = original.chars().take(97).collect();
format!("{}...", t)
} else {
original.to_string()
};
if **count > 1 {
result.push(format!(" [×{}] {}", count, truncated));
} else {
result.push(format!(" {}", truncated));
}
}
if warn_list.len() > 5 {
result.push(format!(
" ... +{} more unique warnings",
warn_list.len() - 5
));
}
}
result.join("\n")
}
fn normalize_log_line(
line: &str,
timestamp_re: &Regex,
uuid_re: &Regex,
hex_re: &Regex,
num_re: &Regex,
path_re: &Regex,
) -> String {
let mut normalized = timestamp_re.replace_all(line, "").to_string();
normalized = uuid_re.replace_all(&normalized, "<UUID>").to_string();
normalized = hex_re.replace_all(&normalized, "<HEX>").to_string();
normalized = num_re.replace_all(&normalized, "<NUM>").to_string();
normalized = path_re.replace_all(&normalized, "<PATH>").to_string();
normalized.trim().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_analyze_logs() {
let logs = r#"
2024-01-01 10:00:00 ERROR: Connection failed to /api/server
2024-01-01 10:00:01 ERROR: Connection failed to /api/server
2024-01-01 10:00:02 ERROR: Connection failed to /api/server
2024-01-01 10:00:03 WARN: Retrying connection
2024-01-01 10:00:04 INFO: Connected
"#;
let result = analyze_logs(logs);
assert!(result.contains("×3"));
assert!(result.contains("ERRORS"));
}
#[test]
fn test_analyze_logs_multibyte() {
let logs = format!(
"2024-01-01 10:00:00 ERROR: {} connection failed\n\
2024-01-01 10:00:01 WARN: {} retry attempt\n",
"ข้อผิดพลาด".repeat(15),
"คำเตือน".repeat(15)
);
let result = analyze_logs(&logs);
// Should not panic even with very long multi-byte messages
assert!(result.contains("ERRORS"));
}
}