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
//! Logs service for managing log file operations
//!
//! Provides business logic for collecting, reading, and filtering log files.
use crate::commands::LogSource;
use anyhow::Result;
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Seek};
use std::path::PathBuf;
/// Service for managing log file operations
pub struct LogsService {
logs_dir: PathBuf,
}
/// Filters for log file collection
#[derive(Debug, Clone)]
pub struct LogFileFilters {
pub node: Option<String>,
pub source: LogSource,
}
/// Filters for log content
#[derive(Debug, Clone)]
pub struct LogContentFilters {
pub pattern: Option<String>,
pub level: Option<String>,
pub lines: Option<usize>,
}
/// A log file with metadata
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct LogFile {
pub name: String,
pub path: PathBuf,
}
/// A log line with source information
#[derive(Debug, Clone)]
pub struct LogLine {
pub source_name: String,
pub content: String,
}
impl LogsService {
/// Create a new logs service
pub fn new(logs_dir: PathBuf) -> Self {
Self { logs_dir }
}
/// Get the logs directory path
#[allow(dead_code)]
pub fn logs_dir(&self) -> &PathBuf {
&self.logs_dir
}
/// Collect log files matching filters
///
/// Returns a map of log file stem names to their paths.
pub fn collect_log_files(&self, filters: &LogFileFilters) -> Result<HashMap<String, PathBuf>> {
let mut sources = HashMap::new();
// Create logs directory if it doesn't exist
if !self.logs_dir.exists() {
std::fs::create_dir_all(&self.logs_dir)?;
return Ok(sources);
}
// Get all log files
let entries = std::fs::read_dir(&self.logs_dir)?;
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
// Check file extension
if path.extension().and_then(|e| e.to_str()) != Some("log") {
continue;
}
// Get filename without extension
let file_stem = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or_default()
.to_string();
// Apply node filter if specified
if let Some(node_name) = &filters.node {
if !file_stem.contains(node_name) {
continue;
}
}
// Apply source filter
let should_include = match filters.source {
LogSource::All => true,
LogSource::Nodes => !file_stem.contains("framework") && !file_stem.contains("service"),
LogSource::Framework => file_stem.contains("framework") || file_stem.contains("cli"),
LogSource::Services => {
file_stem.contains("service") || file_stem.contains("redis") || file_stem.contains("postgres")
}
};
if should_include {
sources.insert(file_stem, path);
}
}
Ok(sources)
}
/// Read logs from multiple sources and apply filters
///
/// Returns all matching log lines with source information.
pub async fn read_logs(
&self,
log_sources: &HashMap<String, PathBuf>,
filters: &LogContentFilters,
) -> Result<Vec<LogLine>> {
let mut all_lines = Vec::new();
// Read all log files
for (name, path) in log_sources {
if let Ok(content) = tokio::fs::read_to_string(path).await {
for line in content.lines() {
// Apply filters
if !self.should_display_line(line, filters) {
continue;
}
all_lines.push(LogLine {
source_name: name.clone(),
content: line.to_string(),
});
}
}
}
// Apply line limit (tail behavior)
if let Some(n) = filters.lines {
let start = if all_lines.len() > n { all_lines.len() - n } else { 0 };
all_lines = all_lines[start..].to_vec();
}
Ok(all_lines)
}
/// Check if a line should be displayed based on filters
pub fn should_display_line(&self, line: &str, filters: &LogContentFilters) -> bool {
// Apply text filter
if let Some(pattern) = &filters.pattern {
if !line.to_lowercase().contains(&pattern.to_lowercase()) {
return false;
}
}
// Apply level filter
if let Some(level) = &filters.level {
let level_upper = level.to_uppercase();
if !line.contains(&level_upper) {
return false;
}
}
true
}
/// Open log files for following (watching)
///
/// Returns a map of readers positioned at the end of each file.
pub fn open_for_follow(
&self,
log_sources: &HashMap<String, PathBuf>,
) -> Result<HashMap<String, BufReader<std::fs::File>>> {
let mut readers = HashMap::new();
for (name, path) in log_sources {
if let Ok(file) = std::fs::File::open(path) {
let mut reader = BufReader::new(file);
// Seek to end
let _ = reader.seek(std::io::SeekFrom::End(0));
readers.insert(name.clone(), reader);
}
}
Ok(readers)
}
/// Read new lines from a reader
///
/// Returns lines that have been added since the last read.
pub fn read_new_lines(
&self,
reader: &mut BufReader<std::fs::File>,
filters: &LogContentFilters,
) -> Result<Vec<String>> {
let mut lines = Vec::new();
let mut line = String::new();
loop {
line.clear();
match reader.read_line(&mut line) {
Ok(0) => {
// No new data
break;
}
Ok(_) => {
// Apply filters
if self.should_display_line(&line, filters) {
lines.push(line.clone());
}
}
Err(_) => {
break;
}
}
}
Ok(lines)
}
}